[Python-Dev] PEP 450 adding statistics module

Steven D'Aprano steve at pearwood.info
Fri Aug 16 04:44:54 CEST 2013


On 16/08/13 04:10, Eric V. Smith wrote:

> I agree with Mark: the proposed median, median.low, etc., doesn't feel
> right. Is there any example of doing this in the stdlib?

The most obvious case is datetime: we have datetime(), and datetime.now(), datetime.today(), and datetime.strftime(). The only API difference between it and median is that datetime is a type and median is not, but that's a difference that makes no difference: both are callables, and being a type is an implementation detail. dict used to be a function that returned a type. Now it is a type. Implementation detail.

Even builtins do this: dict() and dict.fromkeys(), for example. If you include unbound methods, nearly every type in Python uses the callable(), callable.method() API. I am truly perplexed by the opposition to the median API. It's a trivially small difference to a pattern you find everywhere.


> If we do end up keeping it, simpler than the callable singleton is:
>
>>>> def median(): return 'median'
> ...
>>>> def _median_low(): return 'median.low'
> ...
>>>> median.low = _median_low
>>>> del _median_low
>>>> median()
> 'median'
>>>> median.low()
> 'median.low'

That is the implementation I currently have. Alexander has convinced me that attaching functions to functions in this way is sub-optimal, because help(median) doesn't notice the attributes, so I'm ruling this implementation out.

My preference is to make median a singleton instance with a __call__ method, and the other flavours regular methods. Although I don't like polluting the global namespace with an unnecessary class that will only be instantiated once, if it helps I can do this:

class _Median:
     def __call__(self, data): ...
     def low(self, data): ...

median = _Median()

If that standard OOP design is unacceptable, I will swap the dots for underscores, but I won't like it.



-- 
Steven


More information about the Python-Dev mailing list