For example take a simple class representing a person. The only class attribute is a string representing the persons name. I want to make sure that nobody tries to pass the constructor some other type of object like an int, or list…etc. This was my first attempt below I thought that this would return an obj of type None if the argument was not a str but it still seems to return a Person obj. I come from a “more” strongly typed language background and I am a little confused as how to handle my self in python. What does pythonic style say about this situation and type safety more generally? Should I raise an exception? Or find a way to return None? Or something else entirely.
class Person:
name = None
def __init__(self, name):
if not isinstance(name, str):
return None
self.name = name
You’d want to raise an error within the
__init__method:*Note that
basestringalso includesunicodefor python2.x, but isn’t available in python3.x.Careful though, there is nothing here to prevent a user from re-setting the person’s name to a list after the
personhas been constructed.If you want to have this safety built in, you’ll need to start learning about
property.