pythonmoduleinit

Python calling function defined in __init__.py not working


I created sub folder module1 with just __init__.py

def print_hello():
    print('Hello')

__all__ = ["print_hello"]

print('Init loaded')

inside main.py i have

import module1

print_hello()

Output as follows

print_hello()
^^^^^^^^^^^
NameError: name 'print_hello' is not defined
Init loaded

Solution

  • Importing a module does not automatically bring all of its variables and functions into the current namespace (unless you use import *).

    You still have to refer to the specific variable or function you want to use.

    import module1
    module1.print_hello()
    

    or

    from module1 import print_hello
    print_hello()
    

    or

    from module1 import *
    print_hello()