I know that Python is a dynamically typed language, and that I am likely trying to recreate Java behavior here. However, I have a team of people working on this code base, and my goal with the code is to ensure that they are doing things in a consistent manner. Let me give an example:
class Company: def __init__(self, j): self.locations = [] When they instantiate a Company object, an empty list that holds locations is created. Now, with Python anything can be added to the list. However, I would like for this list to only contain Location objects:
class Location: def __init__(self, j): self.address = None self.city = None self.state = None self.zip = None I'm doing this with classes so that the code is self documenting. In other words, "location has only these attributes". My goal is that they do this:
c = Company() l = Location() l.city = "New York" c.locations.append(l) Unfortunately, nothing is stopping them from simply doing c.locations.append("foo"), and nothing indicates to them that c.locations should be a list of Location objects.
What is the Pythonic way to enforce consistency when working with a team of developers?
mypy. But this will not prevent runtime type errors. You could also look intodataclassesc.locations.appendis bad. Provide a method on your object that checks the type before appending. Users of this class should only use that method and shouldn't be touchingself.locationsdirectly. Conventionally, attributes that aren't part of the public API are marked with a single-underscore, so you could use._locationsto let [people know: "don't touch this"l.in VS Code, PyCharm, etc, shows the end user what attributes I expect them to set. I did not realize that they could add any attribute they wanted, which is unfortunate.