[Python-ideas] Conventions for function annotations

Guido van Rossum guido at python.org
Wed Dec 5 19:17:53 CET 2012


On Tue, Dec 4, 2012 at 1:37 AM, David Townshend <aquavitae69 at gmail.com> wrote:
> Just thought of a couple of usages which don't fit into the decorator model.
> The first is using the return annotation for early binding:
>
>     def func(seq) -> dict(sorted=sorted):
>         return func.__annotations__['return']['sorted'](seq)

You've got to be kidding...

> Stangely enough, this seems to run slightly faster than
>
>     def func(seq, sorted=sorted):
>         return sorted(seq)
>
> My test shows the first running in about 0.376s and the second in about
> 0.382s (python 3.3, 64bit).

Surely that's some kind of random variation. It's only a 2% difference.

> The second is passing information to base classes.  This is a rather
> contrived example which could easily be solved (better) in plenty of other
> ways, but it does illustrate a pattern which someone else may be able to
> turn into a genuine use case.
>
> class NumberBase:
>
>     def adjust(self, value):
>         return self.adjust.__annotations__['return'](value)
>
>
> class NegativeInteger(NumberBase):
>
>     def adjust(self, value) -> int:
>         return super().adjust(-value)
>
>
>>>> ni = NegativeInteger()
>>>> ni.adjust(4.3)
> -4

This looks like a contrived way to use what is semantically equivalent
to function attributes. The base class could write

  def adjust(self, value):
    return self.adjust.adjuster(value)

and the subclass could write

  def adjust(self, value):
    return super().adjust(-value)
  adjust.adjuster = int

Or invent a decorator to set the attribute:

  @set(adjuster=int)
  def adjust(self, value):
    return super().adjust(-value)

But both of these feel quite awkward compared to just using a class attribute.

class NumberBase:

  def adjust(self, value):
    return self.adjuster(value)

class NegativeInteger(NumberBase):

  adjuster = int
  # No need to override adjust()

IOW, this is not a line of thought to pursue.

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list