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
following:

http://stackoverflow.com/questions/9305751/force-python-class-member-variable-to-be-specific-type

...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:
    print(s)
    return 3.14

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

if __name__ == '__main__':
    main()
$ python example.py
foobar
<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?

Thanks!
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to