Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: modules and packaging - why isn't __init__.py file executed before __main__.py?
    primarykey
    data
    text
    <p>I have a python program that is entirely contained in a directory with the following structure:</p> <pre><code>myprog/ ├── __init__.py ├── __main__.py ├── moduleone.py └── moduletwo.py </code></pre> <p>I would like to be able to package this and distribute it so that another developer can do <code>pip install -e /path/to/git/clone/of/myprog</code> and can then import myprog in his own programs and do cool stuff with it.</p> <p>I would also like to be able to run myprog at the command line as follows:</p> <pre><code>PROMPT&gt; python myprog </code></pre> <p>When I do this, I expect python to execute the <code>__main__.py</code> module, which it does. However, this module makes references to some functions that are declared in <code>__init__.py</code> and which need to be available both when the program is run at the command line and when it is imported by another program. However, I'm getting the following error:</p> <pre><code>NameError: name 'function_you_referenced_from_init_file' is not defined </code></pre> <p>Do I have to import these functions into <code>__main__.py</code> somehow?</p> <p>I tried a simple example as follows:</p> <pre><code>PROMPT&gt; cat myprog/__init__.py def init_myprog(): print 'running __init__.init_myprog()' PROMPT&gt; cat myprog/__main__.py import myprog print 'hi from __main__.py' myprog.init_myprog() PROMPT&gt; ls -l myprog total 16 -rw-r--r-- 1 iit 63B Aug 30 11:40 __init__.py -rw-r--r-- 1 iit 64B Aug 30 12:11 __main__.py PROMPT&gt; python myprog Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/Users/jon/dev/myprog/__main__.py", line 1, in &lt;module&gt; import myprog ImportError: No module named myprog </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload