Python – local variable is assigned but never used – var=None

Question:

In an attempt to format my code a little better to avoid redundancies in multiple methods doing the same stuff for different classes, I’m faced with the following problem :

# problematic method
def a(self, b, c):
    result = test(b)
    if (result):
        c = None # <- local variable c is assigned but never used
    return

# main code
obj.a(obj.b, obj.c)

And the obj’s variable c is never set to None.

The current working code that I’m trying to reformat is the following :

# working method
def a(self):
   result = test(self.b)
   if (result):
       self.c = None
   return

# main code
obj.a()
Asked By: user3548298

||

Answers:

See Why can a function modify some arguments as perceived by the caller, but not others? for an explanation why reassigning c in a doesn’t update obj.c.

If you want to pass a reference to an object attribute to a function, you have to pass it two things:

  1. the object
  2. the name of the attribute (i.e. a string)

You can then dynamically set that attribute from inside the function:

def a(self, b, name_of_c):
    result = test(b)
    if result:
        setattr(self, name_of_c, None)

obj.a(obj.b, 'c')
Answered By: Aran-Fey

At the end of your def a routine, assign ‘c’ to itself,
it will not make a difference when the code is executed,
since it is declared after the return… this will get
rid of the annoying warning. And it’s simple to
understand when reviewing in the future

def a(self, b, c):
result = test(b)
if (result):
c = None # <- local variable c is assigned but never used
return

#This will never run since it is after the return
#but it will get rid of the annoying assigned but
#never used warning
c = c

Answered By: P_A_N