cheezsteak
cheezsteak

Reputation: 2917

Always include file when importing module in python

How can I have a file that is always imported when then module is imported?

eg: consider this module.

/ myMod
   / __init__.py
   / important.py               # defines myFunc
   / extraFunctions.py
   / classDefinitions.py

All of the functions that anyone using module would be in important.py. I want important.py to be included by default in myMod. So using the module would be like this.

import myMod
myMod.myFunc()

instead of

from myModimport important
important.myMod()

or

import myMod
myMod.important.myFunc()

Should important.py be renamed to __init__.py, main.py or __main__.py or can __init__.py be edited to include important.py as default or even just select functions from it?

Upvotes: 0

Views: 76

Answers (2)

Hai Vu
Hai Vu

Reputation: 40723

In addition to Raydel's answer, I would like to add this point: if your important module contains private functions you don't want to export out, there is a way to control that. Here is an example:

# important.py

# This magic variable controls what gets import via
# from important import *
__all__ = ['dothis', 'dothat']

def dothis():
    pass

def dothat():
    pass

def private1():
    pass

Using the magic variable __all__, you can control which function gets export.

Update

From __init__.py, you can do:

from important import dothis, dothat

This is another way to control which entity (function, variable) get imported.

However, if from __init__.py, you can do this:

import important
important.private1() # OK

or:

from important import private1 # OK, too

That means you can override the __all__ magic variable if you want to. In my opinion, the former method is better since it does not make private1 available to those who import myMod.

Upvotes: 3

Raydel Miranda
Raydel Miranda

Reputation: 14360

You don't have to rename important.py to __init__.py you just have to add to your __init__.py file:

from important import *

that's all.

Upvotes: 3

Related Questions