So, Python is happy for me to write code like,
class A(): pass
a1 = A()
a2 = A()
a1.some_field = 5
a2.other_field = 7
Now, I have learned to stop worrying and love duck typing when it comes to passing objects to methods. And I accept that allowing different instances of a class to have different fields can be convenient sometimes.
My problem is, I'm building a medium-sized web application with a team of 4 developers, and I can't help but think that adding arbitrary fields to objects is going to make it much harder to reason about application state.
I guess my question is this: is the practice of adding arbitrary fields to objects just a natural extension of duck typing, or is it something to be avoided?
Here's a specific example:
class Visitor():
def __init__(self, name, address, dob):
self.name = name
self.address = address
self.dob = dob
def summarize_visits(visits):
self.most_recent_visit = find_most_recent_visit(visits)
In this case, code that deals with Visitor
objects has to be aware of the fact that visitor.most_recent_visit
will raise an AttributeError
unless somebody has previously called summarize_visits
on the same object. Seems like it will lead to a lot of if hasattr(...)
blocks, no?