In the previous post of this series, I suggested prefixing the underscore
_ to variables intended to be short-lived. Here I will discuss another example where variable names lie on their intentions.
Pay attention: people are addicted to the
If you are coding a class, you have some logic in a method, and you are defining a variable within that method, do not use
self. if that variable has no usage outside that method! 😌
When you assign a variable to
self. you are telling the readers of your code that variable (better said, that attribute) has another purpose somewhere else in the execution workflow. Maybe it is even part of the public API. Therefore, someone editing your method will automatically trigger the alarms and search the codebase for a place where that attribute appears before refactoring or recoding your method. The maintainer of your code will get a bit stressed if she/he finds no place anywhere else where that attribute is used. What is happening here?
So, be mindful and express your intentions in your coding. That is, if you define a variable inside a class method, don't use
self. if the scope of that variable does not go beyond that method. Instead, use
self. indeed if that variable is an actual attribute part of the private or public API of the class.
class MegaClass: def method_1(self, arg1, arg2): """Write a docstring ;-)""" var1 = # some logic with arg1. `var1` dies after the method self.var2 = # some logic with var1 and arg2 # self.var2 is an actual attribute of MegaClass part of its API.
Hope this example is clear and you can use it to better express your intentions in your coding 😄
Top comments (0)