python|July 03, 2018|1 min read

Python - Dont Use Static or Class variables with Self

TL;DR

Accessing class variables with self in Python creates instance-level copies instead of referencing the shared class variable; use ClassName.variable instead to avoid unintended behavior.

Python - Dont Use Static or Class variables with Self

While doing code review of one of junior, I encountered following code:

class Test:
  logger = MyLogger.get_instance()
  def __init__(self):
    client = Jira.get_instance()
				
  def do_process(self):
    self.logger.info('Hey test')
				
  # some other code

What bothered me was

  • You have used class variable, and used it with self

*What was the need of declaring it to be class variable

Buggy Part

Lets consider below code:

class Test:
  a = 20
  def __init__(self):
    self.a = 10

test = Test()
print(test.a)

test.a = 10
Test.a = 30
print(test.a)
print(Test.a)
### Output
10
10
30

What are Static or Class variables

These are the variables that are associated with class not with the instance of class. Which means, static or class variables are shared across all instances of the class. There can be an instance variable with the same name as static one. But, both will have a different identifier and can have different values.

The Best practice

Now, you should always refer class or static variable with class name. Although, you can also refere a static variable with class instance. But, it will result into nighmares of your debug life if you declare same name instance variable. Also, if some new developer joins your team and try to read your code. If you have not refered class or static variable with class name, he might consider it an instance variable which it is not.

Always refere statics like:

Test.a

Related Posts

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Introduction This post has the complete code to send email through smtp server…

Python - How to Maintain Quality Build Process Using Pylint and Unittest Coverage With Minimum Threshold Values

Python - How to Maintain Quality Build Process Using Pylint and Unittest Coverage With Minimum Threshold Values

Introduction It is very important to introduce few process so that your code and…

Python - How to Implement Timed-Function which gets Timeout After Specified Max Timeout Value

Python - How to Implement Timed-Function which gets Timeout After Specified Max Timeout Value

Introduction We often require to execute in timed manner, i.e. to specify a max…

How to Solve Circular Import Error in Python

How to Solve Circular Import Error in Python

Introduction To give some context, I have two python files. (Both in same folder…

Python Code - How To Read CSV with Headers into an Array of Dictionary

Python Code - How To Read CSV with Headers into an Array of Dictionary

Introduction Lets assume we have a csv something similar to following: Python…

Python Code - How To Read CSV into an Array of Arrays

Python Code - How To Read CSV into an Array of Arrays

Introduction In last post, we saw How to read CSV with Headers into Dictionary…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…