Search code examples
pythonscopeattributes

Best way to make a variable declared in a method visible in an inner function declaration, in Python?


I have a method which includes: variable declaration, inner functions declarations. I want the variable to be available in the inner functions. All is in a class. All belongs to a code generator, then I can modify only the method content, not the class.

Here are my attempts:

class SomeClassICannotModify(AbstractConditional):
     def __init__(self, a, b):
         .....
 
     def method_which_content_I_can_modify(self):
         myvar = 1  
 
         def my_inner_func():
             global myvar
             myvar = 1
             return myvar

        print(my_inner_func()

Of course, this leads to an error: NameError: name 'myvar' is not defined since global refers to variables declared at module level.

Next attempt without the misused global:

     def method_which_content_I_can_modify(self):
         myvar = 1  
 
         def my_inner_func():
             myvar = 1
             return myvar

Here I get the error: UnboundLocalError: local variable 'cond' referenced before assignment. cond is to be understood after code generation that adds stuff, so read myvar instead.

If I try to pass myvar as an argument like here:

     def method_which_content_I_can_modify(self):
         myvar = 1  
 
         def my_inner_func(v = myvar):
             v = 1
             return v

I get the same error: UnboundLocalError: local variable 'cond' referenced before assignment.

What should I do?


Solution

  • The working solution I could find is as follows:

     def method_which_content_I_can_modify(self):
         myvar = 1  
    
         def my_inner_func(v = myvar):
             v = 1
             return v
    

    This is the last trial I made in the question, the error was for another reason.