Skip to content Skip to sidebar Skip to footer

Correctly Return Variable From Python Module

I'm sure this is absurdly simple but I have been unable to get it working. I want to return the value of x from within my function test in the module 'user_module' to my 'main_pro

Solution 1:

In your module x is defined within the function test. That means that it is only availavle inside the scope of that function. Even if you would try to access x from within the module you would get a name error because x was not globally defined in that module.

This would not work: file: user_module

 def test ():
     x =5
     return x

 print x

Produces a NameError. (that does not mean the general solution is making everything globally available...)

To solve your problem you could create a variable named x. You would have to change your code like this:

import user_module
 x = user_module.test()
 print x

Or instead of printing x you could just print the result of test().

print user_module.test()

Solution 2:

This is because x is defined in a function, which means it is in the function's scope, not in the module's. But your function is returning it — which is good:). So use one of these solutions to get x:

1.

import user_module
print user_module.test()

2.

If you want to pass x from one module to another, then your user_module will look like this:

x = 5

and in the main script you do this:

import user_module
print user_module.x

3.

Or you can do this in your user_module:

def test():
    x = 5
    return x

x = test()

Now in your main script you do this:

import user_module
print user_module.x

Post a Comment for "Correctly Return Variable From Python Module"