Search code examples
pythonstaticstatic-methodsstatic-variables

Python: are static variables discouraged?


I was reading up about static variables (i.e. class variables), static methods, class methods and the nuances of all of these. In languages like C++, static variables are generally strongly discouraged because of many IMO compelling reasons. I was just curious, if the Python community has a known position on static variables being discouraged. The Google Python Style Guide does not seem to have a pro/con position on static variables.

In Python language, are static variables discouraged (i.e. have bad code smell)?

The Google C++ Style Guide's statement "[static variables] cause hard-to-find bugs" certainly seems to ring true to not just C++ language but also Python language.


Solution

  • In some languages, such as Java, static variables can cause problems with testability, as they cannot be easily mocked out. This is not so much the case in Python.

    However, there is less benefit of static and class variables, because when you have values or functions that don't need access to the members of a particular instance, you can just define them at the module level, and use them without reference to a class -- a luxury not available in languages like Java.

    So I would say that static in itself is not a code smell. But if half of your variables are static then I would ask some questions about your understanding of OO design.