ifae/bad_habits/python
Python Bad Habits
Class properties and variables
Do not change the type of a variable or class property
Self explanatory. It forces to check what type of element it is before using it.
Do not Initialize a variable or class property with an uninitialized class instance
Avoid:
class A:
def __init__():
self.prop0 = None
def init_values(prop0):
self.prop0 = prop0
a = A()
# Here a is not really initialized, so it must be checked before using itUse:
class A:
def __init__(prop0):
self.prop0 = prop0
a = A(75)
# Here a is totally initialized and a.prop0 can be used safelyPatterns
Singleton
Avoid using singletons. They make it very difficult to follow the code and maintain it.
Class Factory
The class factory pattern can be used (we may change of idea abruptly on this), but it must be used correctly
Do not implement a Class Factory that generates several class type instances
A class Factory should generate instance of the same class or of classes that inherit from a base class. Inherited classes should have compatible interfaces.
Example:
Avoid:
class InfoFactory:
# Class initialization and some properties and methods
# ...
@staticmethod
def from_unknown(**kwargs):
device_type = kwargs.get("device_type", None)
if device_type == "Type0":
return InformationType0(**kwargs)
if device_type == "Type1":
return InformationType1(**kwargs)
class InformationType0:
# Class initialization and some properties and methods
# ...
class InformationType1:
# Class initialization and some properties and methods
# ...Use:
class InfoFactory:
# Class initialization and some properties and methods
# ...
@staticmethod
def from_unknown(**kwargs):
device_type = kwargs.get("device_type", None)
if device_type == "Type0":
return InformationType0(**kwargs)
if device_type == "Type1":
return InformationType1(**kwargs)
class Information:
# Definition of the interface
class InformationType0(Information):
# Overriden methods
class InformationType1(Information):
# Overriden methodsMain point is that the available methods and properties of the returned instance must be the same
