[Python-ideas] PEP proposal: unifying function/method classes

Chris Angelico rosuav at gmail.com
Sun Mar 25 03:52:09 EDT 2018


On Sun, Mar 25, 2018 at 6:22 PM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Jeroen Demeyer schrieb am 24.03.2018 um 22:38:
>> On 2018-03-24 09:09, Nick Coghlan wrote:
>>> If it was just about introspection, then we could define a new protocol
>>> method or attribute, update the inspect module to respect it, and call
>>> it done.
>>
>> True. In fact, I got a long way by just defining inspect.isfunction as
>>
>> def isfunction(obj):
>>     return hasattr(type(obj), "__code__")
>
> This relies on the fact that Cython attaches an (empty) code object to its
> C implemented functions, which could be considered a hack but is needed for
> things like source file reporting, and also line reporting (although we
> don't currently use that, but an even worse hack).
>
> The main problem, though, is that a lot of code out there does not use the
> "inspect" module but "types" to distinguish its input. That probably got a
> bit better over time with the ABCs, but for things like functions,
> generators and coroutines, I doubt that people would easily consider them.
> "types" just seems too obvious at first thought.
>
> Which suggests that it could help to add a visible note to the CPython docs
> of the "types" module that it's often better to use "inspect" or the ABCs.
> Seems worth a PR.

If people are checking "if type(x) is types.FunctionType", they're
doing it wrong. But if the check is "isinstance(x,
types.FunctionType)", maybe the solution is to register
builtin_function_or_method as a virtual subclass?

ChrisA


More information about the Python-ideas mailing list