Sunday, September 13, 2009

PyDev: Workaround for the Undefined Class/Static Attribute Error

PyDev will incorrectly identify class (static) attributes as "undefined" if they are dynamically added to a class. Consider the following class:
class Quantity:
    def __init__(self, name, unit):
        self.name = name
        self.unit = unit

# Add some class/static attributes after class creation

Quantity.VOLTAGE = Quantity("Voltage", "volts")
Quantity.COUNTS = Quantity("Counts" , "counts")
Now, if we use a class attribute, such as VOLTAGE, PyDev will flag it with an "Undefined variable from import: VOLTAGE" error, even though it is valid.
print(Quantity.VOLTAGE) # <-- Flagged as an error
To work around this, add the annotation @DynamicAttrs to the class's docstring, as follows:
class Quantity:
    """ @DynamicAttrs """
    def __init__(self, name, unit):
        self.name = name
        self.unit = unit
Reference: Fabio on PyDev's user list.