Rule Definition
In Python, a variable under assignment in a given scope will be by default considered as local to that scope (and thus dynamically created when absent). Any variable in the outer scope with the same name will be shadowed. This feature can be handy to screen the effect of global variables within a method, however, shadowing class variables can cause surprising behavior and hard-to-spot bugs. This is particularly the case for the less seasoned Python developers.
Remediation
Depending on the intention of the developer, one possible solution would be to assign the respective values to the class variable (A.x = value, where A is the class) instead of the shadowing instance variable (a.x = value, where a = A()). Otherwise refactoring of the code should be considered.
Violation Code Sample
class A:
x = True
def __init__(self):
if self.x: # access to class variable
self.x = False # self.x refers to an instance variable that shadows A.x
...
Fixed Code Sample
class A:
x = True
def __init__(self):
if self.x:
A.x = False # assignment to the class variable
...
Reference
https://stackoverflow.com/questions/43186844/python-static-class-variables/43200798#43200798
https://stackoverflow.com/questions/68645/are-static-class-variables-possible
https://stackoverflow.com/questions/19902127/what-is-the-pythonic-way-to-avoid-shadowing-variables
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.