harsh poddar
harsh poddar

Reputation: 101

accessing a function's parameter in its child function

I am trying to use a function's parameter in its child function but getting an error that its not defined.

Sample example code is written below: for simplicity parent function is defined as parent and child as child.

def child():
    i += 1
    print(i)

def parent(i):
    print(2*i)
    child()

P.S. I don't want to pass i as parameter in child() as it will not work in my original code.

I have searched and found some solution using classmethods but I want any other possible way.

Upvotes: 1

Views: 903

Answers (3)

Parth Choksi
Parth Choksi

Reputation: 186

If you're okay with having classes and objects, then you might try this workaround..

class xyz:
    
    def child(self):
        self.i += 1
        print(self.i)
    
    def parent(self,i):
        self.i = i
        print(2*i)
        self.child()
        

if __name__ == "__main__":
    xyzObject = xyz()
    xyzObject.parent(5)

Upvotes: 1

milanbalazs
milanbalazs

Reputation: 5329

Basically it is not possible in Pythonic way. @chepner has already describes the background of it in his answer.

You can make "work-around" with globals to see the input variable of parent function. I have written an example but it is totally not Pythonic and it is not recommended.

Example:

def child():
    global child_var
    child_var += 1
    print("Child: {}".format(child_var))

def parent(i):
    global child_var
    print("Parent: {}".format(2*i))
    child_var = i
    child()

child_var = None

parent(5)

Output:

>>> python3 test.py
Parent: 10
Child: 6

Upvotes: 1

chepner
chepner

Reputation: 531315

You cannot. Python is statically scoped; child will not look in the scope of a function from which it is called for a variable definition, only scopes in which it is defined. What you want requires dynamic scoping. (Note: this is a different issue than static vs. dynamic typing, which involves the types of values you can assign to a name.)

Upvotes: 5

Related Questions