Smruti Sahoo
Smruti Sahoo

Reputation: 169

Access a local variable of a function of a module in another module in python

I have a module with the following code in a module named pytest1.py:

def addcount():
    counter = 1
    for x in range(10):
        counter += 1
        if counter == 5:
            count = counter
    print(count)

addcount()

I want to access 'count' variable in another module named pytest2.py I tried :

import pytest1 as p


print(p.addcount.count)

Upvotes: 0

Views: 136

Answers (2)

Prathamesh
Prathamesh

Reputation: 1057

You must return the variable count when addcount() is called such as,

def addcount():
    counter = 1
    for x in range(10):
        counter += 1
        if counter == 5:
            count = counter
    return count

then call the addcount and store the variable returned,

import pytest1 as p

a=p.addcount()
print(a)

Hope this helps you, let me know if anything is incorrect.

Upvotes: 0

Sam Morgan
Sam Morgan

Reputation: 3318

The count variable isn't created until addcount() is called, and it only exists during execution of "pytest1.py", so you can't import it directly. You should have addcount() return count instead of printing it to console.

Upvotes: 1

Related Questions