2

It is possible to assign a class instance variable to a local variable within a method, such as:

class Foo(object):
    def __init__(self):
        self.bar = 'bar'

    def baz(self):
        # assign instance variable to local variable with a method
        bar = self.bar

        # do work with local variable
        bar = "qux"

        # update value of instance variable
        self.bar = bar
        return self

By doing this, one is able to refer to bar instead of self.bar within the scope of Foo.baz().

Is it wrong, or Unpythonic, to do this?

1 Answer 1

6

Doing that is perfectly fine. You could argue that you don’t need to do that (at least in your example, you could reduce the method to two lines if you don’t use the local variable), but there isn’t really any problem with doing it.

There are certain effects which might end up making one or the other way more preferable:

  • Creating a local variable obviously creates another local variable
  • Having a temporary local variable for this requires more code, increasing the overall complexity of the method
  • Accessing a local variable is faster than accessing an instance attribute
  • Having only one point where you update the instance attribute moves the method closer to atomicity (it won’t be purely atomic though) and avoids intermediary values on the attribute
  • Similarly, if accessing or modifying self.bar has side effects, then doing it only once might be desirable over triggering them multiple times

All of these effects are usually super minimal and don’t matter at all. Yet they are there, and just maybe they might become relevant to you. Until then, just use what you are most comfortable with.

Sign up to request clarification or add additional context in comments.

4 Comments

Regarding the point about side effects, accessing it once isn't necessarily better, just different. It might be important to revaluate if its value can change over the course of a loop. Otherwise, this is a good answer. There is no one right or wrong answer, just a lot of factors that contribute to making an informed decision.
@chepner You’re right, adjusted the wording on that part.
Thanks for your useful comments @poke
Don't forget that if you update the local variable you'll need to assign it back to the attribute if you want it to persist after the method ends.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.