DavidJB
DavidJB

Reputation: 2362

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_program'

file: user_module

def test ():
    x =5
    return x

file: main_program

import user_module
user_module.test()
print x

However the above code does not work :( I get the following error

NameError: name 'x' is not defined

Upvotes: 3

Views: 19210

Answers (2)

MentholBonbon
MentholBonbon

Reputation: 755

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

Upvotes: 9

Peter Varo
Peter Varo

Reputation: 12180

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

Upvotes: 7

Related Questions