I'm working on a little side project for work and have made some classes and methods. One of the classes represents a shelf in our inventory and another represents each a bin on the shelf. I have a method to add a new bin to the shelf and I added some logic to make sure it was passed a Location object before it is added to the shelf (right now I'm using lists while I develop before moving everything to a DB).
However I just read in a Python book that I have that it is usually better to handle exceptions as they arise rather than add extra code. I removed the logic to see what error I would get but I didn't get anything it allowed a string in place of the Location object.
Is there a more Pythonic way to enforce what type a parameter is?
What I have for the shelf:
class CrossDock:
locations = []
def add_location(self, location):
if isinstance(location, Location): #if this is commented out it will take what ever is passed to it
self.locations.append(location)
else:
print("location parameter must be of type: Location. Parameter is of type" + str(type(location)))
Is there a way I can do this with a try/except block?
The most pythonic way is to not type check... everything is duck typed.
What's the canonical way to check for type in python?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With