I've noticed a peculiar behavior in how python handles module names.
If I write:
import a.b
import a
and then attempt to reference something in module a.b, it works without a problem.
However, if I attempt something only slightly different:
import a.b
import c as a
and then attempt to reference something in module a.b, I get an error, saying:
AttributeError: 'module' object has no attribute 'b'
I understand that the obvious solution is simply to not have two different modules I refer to by the same name. However, I'm still curious what caused this change in behaviour. Why does one work and not the other?
Why do you expect it to work? All 4 of your import statements are assignments to the variable a. Thus if you assign c to a, it overwrites the contents with something that doesn't have a .b attribute.
Here's what happens in the first case:
import a.b is run, Python loads module a, and then loads the module a.b into the loaded a module's attribute b. It then assigns the result to the variable a.import a doesn't import anything new, because module a is already loaded. It simply reassigns the same module from sys.modules['a'] to a.Here's what happens in the second case:
import a.b is run, Python loads module a, and then loads the module a.b into the loaded a module's attribute b. It then assigns the result to the variable a.import c as a is run, it loads the module c, and then assigns that module to variable a, overwriting the contents (a = sys.modules['c']). You could verify this by comparing the contents of sys.modules['a'] with the contents of a - they'll be different in this case.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With