I’m working on building a custom package for functions I commonly use, and it has several functions that do not fit in any specific module and are used by several modules. I’ve been putting them in __init__.py
, and it works, but I’ve seen many tutorials that recommend a very small __init__.py
. Is there any better place I can put them?
I want to be able to call them like this:
import mypackage #functions in modules mypackage.module.function() #common functions mypackage.function()
Where do I put these functions?
Advertisement
Answer
You could create a ‘utilities’ package/file for storing re-usable pieces of code and then import them into your files which could benefit from them !
And as for your init.py file – I’d leave that empty !
# utilities.py def method(): return None # Some class from utilities import * nothing_burger = method() print nothing_burger
If you add the parent folder to the python path, within the command_line_interface.py or data_access.py file you can import
from extras.utilities import *
and you will have access to all your re-usable methods
. Parent | ├── cli │ ├── __init__.py │ └── command_line_interface.py ├── persistence │ ├── data_access.py │ └── __init__.py └── extras ├── exceptions.py ├── utilities.py └── __init__.py