Skip to content

Instantly share code, notes, and snippets.

@rolandovillca
Last active December 14, 2015 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rolandovillca/6278706547af884042c3 to your computer and use it in GitHub Desktop.
Save rolandovillca/6278706547af884042c3 to your computer and use it in GitHub Desktop.
# When you have __init__.py (blank one), you can import the module using
from dirname import MyModule
# But when you dont have _init_.py at all, you cannot import the module without adding the path till that module to PYTHONPATH.
# In this case from dirname import MyModule FAILS, or reports error.
# If a directory (folder) contains a __init__.py file then it becomes a package.
# What you thought you read was not strictly correct, as you found.
# A package can be imported as if it was a module by itself, and any code in __init__.py is run, although it is often empty.
# Packages are a way of grouping multiple modules together, and you can load them using:
import package-name.module-name
# Packages can also be nested, and often are. Look in the Lib directory under your Python software directory for many examples.
# Files named __init__.py are used to mark directories on disk as Python package directories. If you have the files.
mydir/spam/__init__.py
mydir/spam/module.py
# and mydir is on your path, you can import the code in module.py as
import spam.module
# or
from spam import module
# If you remove the __init__.py file, Python will no longer look for submodules inside that directory,
# so attempts to import the module will fail.
# The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient name,
# hold convenience functions, etc. Given the example above, the contents of the init module can be accessed as
import spam
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment