I have implemented the equivalent of "insert if unique" in Python &
SQLAlchemy to help with data normalization.  However to help minimize the
number of preliminary SELECT statements needed, it helps to check types
through calls to isinstance() before getting to the salient code.
Unfortunately, the code begins to be cluttered with type-checking minutiae.

While researching this problem, I have found potential solutions like the


...but given that Python 3.5 has syntactically understands gradual typing,
I have wondered whether addition of this feature offers anything over use
of property() as described above.  Toy examples have not revealed anything
useful on this front:

$ cat example.py
#!/usr/bin/env python

class Foobar():
    def __init__(self, value):
        self.value = value

def f(s: str) -> int:
    return 3.14

def main():
    i = f('foobar')
    print('i = "{}"'.format(i))
    i = f(Foobar(3))
    print('i = "{}"'.format(i))

if __name__ == '__main__':
$ python example.py
<class 'float'>
i = "3.14"
<__main__.Foobar object at 0x85b8aaac>
<class 'float'>
i = "3.14"

I understand that gradual typing may be useful with static analysis, but I
don't see that any type enforcement occurs by default at runtime.  Am I
missing something here?   Is there a better solution for type enforcement?

Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:

Reply via email to