1

let's start with a basic code that uses a global variable :

def fun():
    print(gvar)
gvar = 3

fun()

that of course prints "3" in the console.

Then, I move my function "fun" in a module "mymod", and do :

from mymod import *
gvar=3
fun()

The result is a NameError exception (gvar is not found)

How can I solve this ? I have to mention that I need to access to various global variables which name is not always the same (the context is complex and I do not describe it now to focus on the problem I have for now)

0

3 Answers 3

2

The only global variables python has, are module scoped. So in your case the variable gvar is not visible in the module mymod.

If you want to use gvar in an imported module, pass gvar as parameter to a function of mymod. If gvar belongs to mymod, define it there.

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

Comments

0

Just move gvar into mymod. You don't even need to import it unless you need to access its value independently.

In other words, don't try to use gvar as a genuine global, but leave it as an implementation detail of mymod.

1 Comment

In the context in which I work it is not possible. I am looking for other solutions.
0

I think you are doing this thing incorrectly, rather than making a variable into one script and trying to execute a function in another script using first variable, you can also send the variable to function header of function!!

So in your case your function will be like

def fun(var): 
    print(gvar)

And Call Your Function From Another Script With:

gvar = 5
fun(gvar)

1 Comment

Thanks for your answer, however it is not corresponding to my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.