When writing your own package in Python, should __init__.py contain imports like os, sys? Or should these just be imported within the file that is using them?
1 Answer
Import the modules in the module that uses them.
Placing import os in __init__.py would put os in the package's global namespace, but it would not affect the namespace of the module that uses os. Global namespaces are not shared across modules or packages, so you would get NameErrors if you did not import them in the module that uses os.
3 Comments
Ian Stapleton Cordasco
Putting
import os however in __init__.py will affect any module that does from my_awesome_package import * because now they'll have the os module in their namespace affecting possible functions or global variables unexpectedly. While using * is frowned upon, enough people still use it and package authors should be considerate even of themmartineau
@sigmavirus24: Many modules and packages are designed specifically to support the
from xxx import * coding-style and do so by defining a module- or package-level variable named __all__ which contains a sequence of strings of the names of things defined by it (excluding anything not mentioned). For packages that is often created in the __init_.py file.Ian Stapleton Cordasco
@martineau I'm well aware of that. OP was asking about putting that in there without mentioning that or anything else so I addressed the concerns with doing that and nothing else.