I need some clarification on how module and class level imports are handled when coexisting in the same namespace. See the following examples:
Works:
import datetime
print datetime.datetime.utcnow()
Fails:
from datetime import datetime
print datetime.datetime.utcnow()
Error: AttributeError: type object ‘datetime.datetime’ has no
attribute ‘datetime’
Works:
from datetime import datetime # Is this ignored?
import datetime
print datetime.datetime.utcnow()
What exactly is happening in the 3rd example? Is the second module import replacing the class-specific first import? Does this mean that module and class level imports shouldn’t be mixed in the same namespace?
There is no priority is such. The outcome is determined by the order in which
importstatements are executed, as follows.If you try to import several things called
Xinto your namespace, each import would rebindXto whatever it’s importing.Therefore at the end it will be last import that’ll be in effect as far as the name
Xin concerned.This is precisely what happens in your third example: