Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import two or more modules with the same name in Python?

Here's the code which is causing me trouble:

import time
from time import time

time.sleep(1)
start=time()
input=raw_input(' ')
end=time()
time.sleep(1)

print (start - end)

The issues are the following two imports with the same name as time:

import time

from time import time

How can I access both of these modules in my code? I need to use both the following lines in my code:

lines time()
and time.sleep()

But once imported, second module overrides the first one.

like image 291
smart Avatar asked Oct 18 '25 15:10

smart


1 Answers

How to import two or more modules with the same name?

Python provides the way to import modules with an alias. For example in your case, you may do:

import time as t   # access "time" as "t"
from time import time as tt  # access "time.time" as "tt"

In order to use, just use the alias as:

t.sleep(1)   # equivalent to "time.sleep(1)"

start = tt()  # equivalent to "start = time.time()"

In fact you can also store the imported modules in variables and aceess it later:

import time
t = time

from time import time
tt = time

But why to do this when Python already supports aliases?


Better approach for your scenario

My above answer is aimed at any such general scenario. Though for your's specific problem Turksarama's answer makes more sense , because time.sleep and time.time belongs to same module. Just import them and use them together. For example:

import time

time.sleep(10)
time.time()

OR,

from time import time, sleep

sleep(10)
time()
like image 155
Moinuddin Quadri Avatar answered Oct 21 '25 03:10

Moinuddin Quadri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!