SchwabTheDeck
SchwabTheDeck

Reputation: 321

Accessing variables that are inside a function

I was looking all over for any kind of small example or something to help me and I couldn't find it. I feel like I am missing something obvious. I have a large function in one .py file that I want to call in another .py file and use all the variables from the function and I couldn't do it. So I was trying to do it with a small example and still can't get it. Say I have a file mod1.py that contains:

def mod(num):
    a = 5
    b = 6
    c = num

I tried adding all kinds of returns to it and still couldn't get it to work. But I call it in a file named mod_read.py:

import mod1

mod1.mod(1)
d = mod1.mod.a
print(d)

When I run mod_read.py I get the error: "AttributeError: 'function' object has no attribute 'a'". What obvious thing am I missing?

Upvotes: 2

Views: 75

Answers (3)

martineau
martineau

Reputation: 123453

You can return multiple values from a function as tuple:

def mod(num):
    a = 5
    b = 6
    c = num
    return (a, b, num)

Then in the other file, use it something like this:

import mod1

d, b, num = mod1.mod(1)
print(d)    

Upvotes: 1

Marcin
Marcin

Reputation: 49826

You don't use variables from another function. You call a function, and you get its return value - that is the point of a function (or to cause whatever side effects it causes).

If you want a thing which stores values in variables, you want to use objects. Define a class.

In your particular example, I don't know what "all kinds of returns" means, but if you want the function to return a, just do return a:

def mod(num):
    a = 5
    b = 6
    c = num
    return a

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

  1. Local variables only exist while the function is being run.
  2. Local variables are never attributes of their containing function.

If you want to get values from a function then you need to return them from it. Otherwise, look into OOP if you need more persistence.

Upvotes: 6

Related Questions