[Python-ideas] Conventions for function annotations

Ben Hoyt benhoyt at gmail.com
Wed Dec 5 20:52:08 CET 2012


> - Tuples. Sometimes you want to say e.g. "a tuple of integers, don't
> mind the length"; other times you want to say e.g. "a tuple of fixed
> length containing an int and two strs". Perhaps the former should be
> expressed using ImmutableSequence[Int] and the second as Tuple[Int,
> Str, Str].

Nice, that seems very explicit. ImmutableSequence is long, but clear.
In this specific case, should it be just Sequence, and a mutable one
would be MutableSequence (to be consistent with collections.abc
names?).

> - Unions. We need a way to say "either X or Y". Given that we're
> defining our own objects we may actually be able to get away with
> writing e.g. "Int | Str" or "Str | List[Str]", and isinstance() would
> still work. It would also be useful to have a shorthand for "either T
> or None", written as Optional[T] or Optional(T).

Definitely useful to have a notation for "either T or None", as it's a
pretty heavily-used pattern. But what about using the same approach,
something like "T | None" or "T | NoneType". Though if you use the
real None rather than experimental_type_annotations.None, is that
confusing? In any case, it seems unnecessary to have a special
Optional(T) notation when you've already got the simple "T1 | T2"
notation.

> - Whether to design notations to express other constraints. E.g.
> "integer in range(10, 100)", or "one of the strings 'r', 'w' or 'a'",
> etc. You can go crazy on this.

Yes, I think this is dangerous territory -- it could get crazy very
fast. Statically typed languages don't have this. Then again, I guess
type annotations have the potential to be *more* powerful in this
regard. Still, it'd have to be an awfully nice and general notation
for it to be useful. Even then, your "def" line complete with
type/constraint annotations may get far too long to be readable...

-Ben



More information about the Python-ideas mailing list