简体   繁体   中英

Static typing for `__slots__` in python

I know that python used duck typing, but I was wondering whether it is possible to enforce type validation for class variables, __slots__ in particular.

for example -

class Student:
def __init__(self, name):
    self.name = name

class Class:
    __slots__ = ('class_representative',
                 'var_2',
                 'var_3',
                 '...',  # Assume many more variables below
                )

    def __init__(self, *args, **kwargs):
        self.class_representative = kwargs.get('cr')
        self.var_2 = kwargs.get('v2')
        self.var_3 = kwargs.get('v3')
        ... # Assume many more variables below

In the above example, how do I make sure that whenever any object gets assigned to the class_representative variable, it should always be of type Student ?

Is something like the following possible?

class Class:
    __slots__ = ('class_representative': Student,
                 'var_2',
                 'var_3',
                 '...',  # Assume many more variables below
                )

When you say "static typing", I assume you're referring to PEP 484 . In that case, __slots__ makes absolutely no difference, and we annotate the type of instance variables the way we always do for Python classes.

class Class:
    __slots__ = ('class_representative',)
    class_representative: Student

    def __init__(self, student: Student) -> None:
        self.class_representative = student

Incidentally, if you're going for static type checking in Python (which I highly recommend; it's a surprisingly well-designed system), taking and forwarding *args and **kwargs in your constructor is an excellent way to lose any static verifiability. Take the arguments you need, with as explicit of types as you can manage to provide, and forward what you have to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM