Re:Python 3 Types in the Wild
by lolive on Friday March 18, 2022 @11:01AM
(#30723165)
With this type system is it possible to subclass string and int, to enforce types for, let’s say, firstName, postalCode, etc.
[ Parent
| on HN ]
Re:Python 3 Types in the Wild
by ghostwriter on Friday March 18, 2022 @12:06PM
(#30723978)
yes, but the current way of defining it [1] is not very elegant:
FirstName = NewType('FirstName', str)
PostalCode = NewType('PostalCode', str)
[1] https://docs.python.org/3/library/typing.html#newtype
Re:Python 3 Types in the Wild
by paisawalla on Friday March 18, 2022 @11:57AM
(#30723849)
Yes, simply
FirstNameType = str
(But don't use ints for postal codes, even if the postal codes are numeric)Huuum. If I sign a function so it only accepts a FirstNameType, and I use the statement you propose, won’t any string be acceptable as an input parameter, from the type system point of view?
Yeah, that is the syntax for a type alias. You can use NewType to create an actual subclass of the type instead. https://docs.python.org/3/library/typing.html#newtype
Re:Python 3 Types in the Wild
by paisawalla on Friday March 18, 2022 @06:11PM
(#30728195)
In that case, you need a subclass of string that does nothing but has its type as FirstNameType. Wherever you create or return strings that are first names, you'll need to instantiate FirstNameType instead.
Re:Python 3 Types in the Wild
by colejohnson66 on Friday March 18, 2022 @01:41PM
(#30725194)
> ... even if the postal codes are numeric
Maybe in the US. In Canada, they are 6 characters of letter-digit-letter-digit-letter-digit (in regex: /((?:[A-Z][0-9]){3})/)
And in the future, they could be anything. Finland expanded the allowed characters in person identification numbers to support people born after 2000. Usually bad idea to be too strict in checking fields where people manually enter text.