smart
smart

Reputation: 161

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.

Upvotes: 4

Views: 5811

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

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()

Upvotes: 10

Turksarama
Turksarama

Reputation: 1136

I would import sleep seperately.

from time import time, sleep

sleep(1)
start=time()
# changed input to inp, input is already an inbuilt function so you shouldn't shadow it.
inp=raw_input(' ')
# you had end = sleep(1) here, but sleep returns None
sleep(1)
end=time()

print (start - end)

Upvotes: 3

Related Questions