[Python-3000] Questions on optional type annotations
Nick Coghlan
ncoghlan at gmail.com
Fri May 12 10:39:23 CEST 2006
Collin Winter wrote:
> This exact thing (Function(type, type, ..., returns=type)) has been
> kicked around for inclusion in typecheck. One problem with using a
> keyword arg to indicate the return type means that functions passed in
> can't use that keyword argument themselves (unless you're not going to
> allow Function(arg1=type, arg2=type, ...)-style type annotations).
>
> One solution to this might be that you can't use Function inline,
> using an attribute to declare the return type (which should default to
> None). This lends itself to solving the next issue...
[snip]
> Maybe we could let the user decide which mode to use. If we use an
> attribute to declare the return type, we could use another to indicate
> whether they want this particular Function() instance to be strict or
> lenient.
Both of these (return type annotation and selecting strict or lenient
behaviour) can be done inline with the right methods on the annotation object.
class Annotate(object):
def __init__(*args, **kwds):
self, args = args[0], args[1:]
self.arg_notes = args
self.kwd_notes = kwds
self.return_note = None
self.strict = False
@classmethod
def strict(*args, **kwds):
cls, args = args[0], args[1:]
self = cls(*args, **kwds)
self.strict = True
return self
def returns(self, note):
self.return_note = note
return self
def __call__(self, func):
func.__signature__.update_annotations(self)
return func
@Annotate(str, str, int).returns(int)
def f(a, b, c=0):
# some operation producing an int. . .
@Annotate.strict(str, str, int).returns(int)
def f(a, b, c=0):
# some operation producing an int. . .
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://www.boredomandlaziness.org
More information about the Python-3000
mailing list