initialization – python __main__ and __init__ proper usage

initialization – python __main__ and __init__ proper usage

I made:


with the 2 files being:

import __main__
print(in init)
print(init name,__name__)


print(main name,__name__)
print(in main)    
if __name__==__main__:
    print(in main main block)

If I run __main__ directly:

1538:~/mypy$ python foo/
(main name, __main__)
in main
in main main block

It does same thing if I invoke the directory. It does not import

1541:~/mypy$ python foo
(main name, __main__)
in main
in main main block

But from a shell, it loads both files

1542:~/mypy$ python
>>> import foo
(main name, foo.__main__)
in main
in init
(init name, foo)

But it does not use the if __name__ block of __main__ – the name isnt right, its now foo.__main__.

relevant docs

Execute the Python code contained in script, which must be a filesystem path (absolute or relative) referring to either a Python file, a directory containing a file, or a zipfile containing a file.

This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:

I created another directory with an but no main:

1558:~/mypy$ python foo1
/usr/bin/python: cant find __main__ module in foo1
1558:~/mypy$ python
>>> import foo1
(in init, foo1)

import works, but I cant run the directory.

Is useful for import (all subdirectories are search for import)


if __name__ == __main__:

is use to run a module itself. But this par of code would not be executed if imported in other script

initialization – python __main__ and __init__ proper usage

So, as stated in question for such C code

void func1(){...} //in code1.c
void func2(){...} //in code2.c
#include header.h
int main() //in main.c 
    return 0;

there is some kind of python solution:

def func1() #  in in package Foopackage
def func2() #  in in package Foopackage

as follows

import Foopackage.function1 as f1
import Foopackage.function2 as f2

def main():

if __name__ == __main__:

No required. In my case assumed that all files are located in same directory.

Any corrections are welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *