I’m currently going through a basic compsci course. We use Python’s in a lot. I’m curious how it’s implemented, what the code that powers in looks like.
I can think of how my implementation of such a thing would work, but something I’ve learned after turning in a couple homework assignments is that my ways of doing things are usually pretty terrible and inefficient.. So I want to start investigating ‘good’ code.
The thing about builtin functions and types and operators and so on is that they are not implemented in Python. Rather, they’re implemented in C, which is a much more painful and verbose programming language that won’t always translate well to Python (usually because things are easier some other way in Python.)
With that said, you can investigate all of Python’s implementation online, via their public source repository.
The implementation for
inis scattered — there’s one implementation per type, plus a more general implementation that calls the type-specific implementation (more on that later). For example, for lists, we’d look for the implementation of lists. In the Python source tree, the source for all builtin objects is in the Objects directory. In that directory you’ll find listobject.c , which contains the implementation for the list object and all its methods.On the repository at the time of answering, if you look at line 393 you’ll find the implementation of the in operator (also known as the
__contains__method, which explains the name of the function). It’s fairly straightforward, just loops through all the elements of the list until either the element is found, or there’s no more elements, and returns the result of the search. 🙂If it helps, in Python the idiomatic way to write this would be:
I said earlier that there was a more general implementation. That can be seen in the implementation of
PySequence_Containsinabstract.c. It tries to call the type-specific version, and if that fails, resorts to regular iteration. That loop there is what a regular Python for loop looks like when you write it in C (using the Python C-API).