Python calling function defined in __init__.py not working

42 Views Asked by At

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
1

There are 1 best solutions below

0
John Gordon On BEST ANSWER

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()