0

I am trying to set acceptable built-in types for my class variables. I want to throw an exception if given type is incorrect. Is there any better way than setter with isinstance()?

My first attempt:

class Address:
    city: str
    building_number: str or int
    apartment_number: int
    street: str

    def __init__(self, city, building_number, apartment_number, street):
        self.city = city
        self.building_number = building_number
        self.apartment_number = apartment_number
        self.street = street

Unfortuantely it compiles regardless of type.

My second attempt:

class Address:
    def __init__(self, city: str, building_number: str, apartment_number: int, street: str):
        self.city = city
        self.building_number = building_number
        self.apartment_number = apartment_number
        self.street = street

This one actually shows the wrong type when creating a class but it compiles without throwing any error or message.

enter image description here

enter image description here

2 Answers 2

2

isinstance() is a safe way, but if you want just to type less, you may use the type checking that is done by "+" operator like below

class Address:
    city: str
    building_number: str or int
    apartment_number: int
    street: str

    def __init__(self, city:str, building_number:str, apartment_number:int, street:str):
        self.city = "" + city
        self.building_number = "" + building_number
        self.apartment_number = 0 + apartment_number
        self.street = "" + street

x = Address(1, "a", "b", "c")

And the stacktrace message is meaningful:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    x = Address(1, "a", "b", "c")
  File "test.py", line 9, in __init__
    self.city = "" + city
TypeError: must be str, not int
Sign up to request clarification or add additional context in comments.

Comments

0

I tried this and I get no an error:

class Address:
    def __init__(self, city: str, building_number: str, apartment_number: int, street: str):
        self.city = city
        self.building_number = building_number
        self.apartment_number = apartment_number
        self.street = street

a = Address(1, "asassa", "shoudbeanint", "asas")

print (a.city)
print (a.apartment_number)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.