Is Python module counter () using C?

When I use the function:

from collections import Counter

      

Is counter () obtained using C structs? Is there a convenient way to determine what is common for this and other functions?

Give Python the open source what should I look for in the source code if this is the best way to determine if a given function is using C structs?

+3


source to share


1 answer


There is no direct way to assert this for classes, but there is a way to determine if a function or method was written in C. Thus, any class written in C probably defines at least one explicit or implicit function in C (if not it will difficult) and you can check inspect.isbuiltin

:

>>> import collections
>>> import inspect
>>> def is_c_class(cls):
...     return any(inspect.isbuiltin(getattr(cls, methname, None)) 
...                for methname in cls.__dict__)

>>> is_c_class(collections.Counter)
False

>>> is_c_class(dict)
True

      

However, that's not all, because the collections.Counter

calls collections._count_elements

, which is a C function:

>>> inspect.isbuiltin(collections._count_elements)
True

      

So, you should always check out the source code ( The Pythons repository is on github , and also the implementation for Counter

).




Please note that the above using validation isbuiltin

has some disadvantages. For example, you might have a class attribute that is a C function:

>>> class Test(object):
...     c_function = all  # builtin all function is a C function

>>> is_c_class(Test)
True

      

So don't rely on it for always giving correct results, treating it as an approximation.

+2


source







All Articles