0

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?

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You're right! This is important. I forgot that. +1.
Could I alternatively do from important import dothis, dothat in __init__.py? So if another module file imports important.py that file can access those private functions? Or does __all__ only effect from x import * and not import x?
3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.