I believe the Python term for this is "monkey-patching"; here's some related information:
Stack Overflow - monkey patching
A benefit of this is that your python code is very dynamic; you can add fields to customize a class, module, or any Python construct with attributes.
One very clever use of this is the "Bunch" python recipe, which defines a general-purpose container that can be constructed using keyword arguments:
Bunch recipe
A cost is in potential maintenance issues; it is difficult to track where a class or module was last "monkey-patched".
Of course, if you're really into duck typing, your code that uses some_field
and other_field
ought to try/except
to make sure that the attributes are really present, and handle both cases.
In your specific example, it seems like Visitor.most_recent_visits
could be initialized to None
, or some other sentinel. IMHO, if you can initialize an attribute to a value that makes sense in the constructor, you should do so, and only reserve "monkey-patching" for extreme cases. Also, monkey-patching of library classes and functions seems like trouble.