How to force an attribute to be int in python?

Viewed 663

I have the following class:

class C3DPoint(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    # Other methods

I want to be sure that if somebody sets v3dpoint.x = <sth> it throws an error in case vale is not string.

How can this be done?

4 Answers

Good Python design avoids explicit type-checking: "if it quacks like a duck, it's a duck...". Therefore, you should first try to perform your data validation outside your class, or not at all.

Having said this, one way to perform your check is to redefine __setattr__ as described here:

class Point():

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def __setattr__(self, name, value):
        assert isinstance(value, str), "Value must be of type str"
        super().__setattr__(name, value)

p = Point('a', 'b', 'c')
p.x = 3

# AssertionError: Value must be of type str

You can type your function parameters in Python, assuming you use a current version, currently not sure which PEP implemented it.

def __init__(x: int, y: int , z: int):

This however will not throw TypeErrors, since we are all consenting adults, for that you'd can do a type check.

if not (isinstance x, int):
    # throw Error

You can do it like that:

variable_name: type = value

Use a try/except:

try:
    int(a)
except Exception as e:
    print "That's not an int"
Related