Dance Party2 Dance Party2 - 2 months ago 5x
Python Question

Python Get Returned Object From Called Module

Given this module (

def calculation(x):
r = x + 1
return r

In my main .py file in Spyder, I'm calling it like this:

import sample
b = sample.calculation(2)

My (dumb) question is:
how to I access r, as defined in the sample module, for other calculations in the main .py file from which I'm calling sample?

I want to continue by doing something like:

a = r/2

in the main .py file after calling



I would assume b would result in the number 3.
But what if the module returns 2 different numbers (objects)? How do I access them individually?


Accessing another module's variable is possible by making it global. But it is not a good practice and often avoided. You can do this instead

import sample
r = sample.calculation(2)

This way, you can use the same variable name 'r' but it is now a local variable.

For your second question about returning multiple objects from a module, you can do this

def module1(x):
    return x+1,x+2

a,b = module1(5)
#a has 5+1 = 6 
#b has 5+2 = 7