How are functions built at a lower level?


#1

Hiya

So Python has basic functions such as len(), str(), int() etc which are integrated into every module, from what I understand.
And then we have libraries such as the math library.

Am I understanding correctly that libraries such as math, store functions which are built from lower level python code and integrated functions such as len() are built from C?
Or not necessarily?

If my understanding is incorrect, how come then some functions get stored in libraries which you need to import and others are integrated which you don't need to import?

Also, how can I look into a functions body? Say, I wanna see how the function max() works, how can I look up what's inside it?

Thank you


#2

That's all about organisation - doesn't matter how they're implemented.
Not loading all modules in existence also helps a whole lot with start-up time (which is really important for small scripts that are expected to not take a noticeable amount of time)

Generally the things that are used very often are C code for performance reasons (so things like strings and lists) while things that don't do anything heavy are implemented in Python. Some things can't be implemented in Python itself because it relies on low level stuff, for example any I/O (files, network).

len doesn't figure out the length itself, the datastructure in question has to do that - len is therefore pretty much just an alias for:

>>> [4].__len__()
1

There's probably a bunch of error checking or some such as well though.

Similarly, max will iterate through the datastructure, and the code to iterate will be with the datastructure, since that'll be different for each datastructure.

CPython (the reference implementation, what you'll most likely use when you run Python) is open source, you can find the code here: https://hg.python.org/cpython/file/tip (currently version 3.7)

You can find max here:
https://hg.python.org/cpython/file/tip/Python/bltinmodule.c
If you look near the bottom of the file you can find where they pair the python name with the corresponding function/object, in this case max is the builtin_max function which in turn uses min_max where there's a whole lot of code just for error-checking, and generalising and what not. The part that matters is it = PyObject_GetIter(v); which it then keeps asking for next value while (( item = PyIter_Next(it) )) { and compares int cmp = PyObject_RichCompareBool(val, maxval, op);


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.