1

I have two .py files in the same folder: file1.py and file2.py.

file1.py

def hello():
    print("hello world")

file2.py

from file1 import hello
reload(file1)
hello()

Why do I get the error:

NameError: name 'file1' is not defined
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
g2m.agent
  • 170
  • 1
  • 11
  • 2
    @n1c9: No. That will not help and will only open the way for more problems. This problem has nothing to do with `__init__.py`. – user2357112 Feb 14 '21 at 05:49
  • 1
    Also: as a complete aside, don't use `[tag:...]` for *formatting* purposes, that is meant for linking to a tag page on the site itself. You can use backticks instead, i.e. `\`file1.py\``. – costaparas Feb 14 '21 at 05:52

3 Answers3

2

from A import B means that just import B which is in A. Not import A

You import hello() function not file1.

If you want to reload file1, just import file1.

like this:

from imp import reload
import file1
reload(file1)
file1.hello()

Additionally, if you use python 3.X version, you need to add

from imp import reload

or

from importlib import reload

JAEU
  • 36
  • 4
2

reload() reloads a previously imported module. See https://docs.python.org/3/library/importlib.html#importlib.reload.

from file1 import hello only imports hello() which is a function, not a module.

Also, reload(module) is available for Python versions <= 3.3. For Python versions >= 3.4, use importlib.reload(module).

The proper way is

import importlib

import file1

file1.hello()

importlib.reload(file1)
file1.hello()
yoonghm
  • 4,198
  • 1
  • 32
  • 48
-1

I am not an expert but did you try this,

from file1 import hello as q
reload(q)
hello()