0

I need to understand how to solve the Name Error 'not defined'. So I made a code example below.

I have to files in the root directory, one must be used as a module. The first file is main and the second file is additional which I need to use as a module. So I have to move a function name greet() from the main to additional together with the global variable.

When I move the function from main to additional I have to import additional to main. The error that I get is global variable is not recognized. How do I import a module in such a way that I avoid the 'not accessed' or 'not defined' error message.

THIS IS main file before moving the greet function.

#global name = 'Leo' def greet(): global name print(f'Hello {name}!') greet() def do(): global name print(f'How is your day {name}?') do() 

THIS IS additional with the code taken from main

#global name = 'Leo' def greet(): global name print(f'Hello {name}!') greet() 

THE main should now be like this

def do(): global name print(f'How is your day {name}?') do() 

1 Answer 1

1

If you use just a generic import statement, things contained in the imported module will be added to namespace prepended with name of the module like so:

import additional def do(): print(f'How is your day {additional.name}?') do() 

You can import specific things from a module, then imported object will not have anyting added to it's name:

from additional import name def do(): print(f'How is your day {name}?') do() 

In both cases you can notice that greet() from additional is also executed. That is because when importing something, that imported module is being executed like any other Python code.

If you want to avoid that, make sure to add very common piece of code in Python scripts:

if __name__=="__main__": greet() 

This will make sure that anything contained in this if statement is only executed when the module is run as an entrypoint for the program.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.