I have this package:
mypackage/
__init__.py
a.py
b.py
And I want to import things from module a to module b, does it make sense to write in module b
from mypackage.a import *
or should I just use
from a import *
Both options will work, I’m just wondering which is better (the 2nd makes sense because it’s in the same level but I’m considering the 1st to avoid collisions, for example if the system is running from a folder that contains a file named a.py).
You can safely use number 2 because there shouldn’t be any collisions – you’ll be always importing a module from the same package as the current one. Please note, that if your module has the same name as one of the standard library modules, it will be imported instead of the standard one. From the documentation:
The option
from mypackage.a import *can be used for consistency reasons all over the project. In some modules you will have to do absolute imports anyway. Thus you won’t have to think whether the module is in the same package or not and simply use a uniform style in the entire project. Additionally this approach is more reliable and predictable.Python style guidelines don’t recommend using relative imports:
Since python 2.5 a new syntax for intra-package relative imports has been introduced. Now you can
.to refer to the current module and..referring to the module being 1 level above.