Home > Software engineering >  Change class attribute type from string to int
Change class attribute type from string to int

Time:06-30

I have this class that should be initialized with all parameter int but sometimes it gets string instead of int

@dataclass
class Meth:
    one: Optional[int] = None
    two: Optional[int] = None
    three: Optional[int] = None


my_class = Meth(one="1",two=2,three=None)

As you can see in attribute one there is bad type. And to fix this my first thought was to create it again like this

new_class = Meth(one=int(my_class.one),two=int(my_class.two),three=int(my_class.three)

but I get this error because three is None

TypeError: int() argument must be a string, a bytes-like object, or a real number, not 'NoneType'

So my question is what would be the best way to change all attribute types to the correct type.

CodePudding user response:

The error is caused when converting None to int, not because of specified types. You can add a check:

new_class = Meth(
   one=int(my_class.one),
   two=int(my_class.two),
   three=my_class.three if my_class.three is None else int(my_class.three)
)

A better way would be to do it while initializing the class

class Meth:
    one: int = None
    def __init__(self, 
            one: Optional[Union[str,int]] = None,
            two: Optional[int] = None,
            three: Optional[int] = None):
    # Do the checks and assign values
    if one is not None:
        self.one = int(one)

Or by using a library for data validation, pydantic or alike:

from pydantic import BaseModel

class Meth(BaseModel):
    one: int
    two: Optional[int]
    three: Optional[int]

my_class = Meth(one="1",two=2,three=None)
assert type(my_class.one) is int
  • Related