🌐
Python
docs.python.org › 3 › c-api › code.html
Code Objects — Python 3.14.3 documentation
Changed in version 3.12: Renamed to PyUnstable_Code_NewWithPosOnlyArgs. The old name is deprecated, but will remain available until the signature changes again. PyCodeObject *PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)¶ · Return value: New reference. Return a new empty code object with the specified filename, function name, and first line number.
🌐
Python
docs.python.org › 3 › c-api › function.html
Function Objects — Python 3.14.4 documentation
This is an instance of PyTypeObject and represents the Python function type. It is exposed to Python programmers as types.FunctionType. ... Return true if o is a function object (has type PyFunction_Type). The parameter must not be NULL. This function always succeeds. PyObject *PyFunction_New(PyObject *code, PyObject *globals)¶
Discussions

Executing code objects from `fn.__code__` vs code objects from compile
In the below code, def foo(): a = 5 b = 7 print ('a + b =', a + b) exec(foo.__code__) it correctly prints a + b = 12 but the following does not print anything. import inspect def foo(): a = 5 b =… More on discuss.python.org
🌐 discuss.python.org
0
0
April 30, 2024
python - Using objects as functions - Stack Overflow
I fail to understand a particular program in the book, chapter 7 - Python Object-oriented Shortcuts. The extended version of the code is available here · Although the program comes under the topic Functions are objects too, the provided program also uses a strange code, which i feel, more ... More on stackoverflow.com
🌐 stackoverflow.com
Are functions objects in Python? - Stack Overflow
The above creates 3 objects without ever calling a type, Python did that all for you based on the syntax used. The same applies to functions. Creating one yourself can be a little more complex; you need to have a code object and reference to a global namespace, at the very least: More on stackoverflow.com
🌐 stackoverflow.com
Understanding custom made functions
They covered functions in the first week of the course. A function defines deferred behavior. Deferred, because the behavior doesn’t occur when you define the function, but later, when you call the function. Deferred behavior is the difference between telling someone how to bake a cake, and telling someone to bake a cake. A function relates input to output. The input of a function is its parameters (if it has any) and the output is its return value, indicated by the use of the return statement. More on reddit.com
🌐 r/learnpython
8
1
January 18, 2025
🌐
Stack Overflow
stackoverflow.com › questions › 78716221 › is-there-any-way-to-construct-a-code-object-from-a-code-string-and-assign-it-to
Is there any way to construct a code object from a code string and assign it to an existing function using Python? - Stack Overflow
I've managed to access the byte code sequences of the function's __code__.co_code attribute, like this: def func1(): return 1 code_obj = func1.__code__.co_code print(code_obj) # prints b'd\x01S\x00' new_code = b'd\x01S\x00' # copied the original code bytes sequence. How am I going to write `return 0` in bytes? func1.__code__.co_code = new_code print(func1) code_obj2 = func1.__code__.co_code ... Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2024.1\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode coro = func() File "<input>", line 7, in <module> AttributeError: readonly attribute
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.4 documentation
February 27, 2026 - [1] If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section File input in the Reference Manual).
🌐
Python.org
discuss.python.org › python help
Executing code objects from `fn.__code__` vs code objects from compile - Python Help - Discussions on Python.org
April 30, 2024 - In the below code, def foo(): a = 5 b = 7 print ('a + b =', a + b) exec(foo.__code__) it correctly prints a + b = 12 but the following does not print anything. import inspect def foo(): a = 5 b =…
🌐
W3Schools
w3schools.com › python › ref_func_object.asp
Python object() Function
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... The object() function returns an empty object. ...
🌐
Readthedocs
python-textbok.readthedocs.io › en › 1.0 › Functions.html
Functions — Object-Oriented Programming in Python 1 documentation
Defining a function does not make it run – when the flow of control reaches the function definition and executes it, Python just learns about the function and what it will do when we run it. To run a function, we have to call it. To call the function we use its name followed by round brackets ...
Find elsewhere
🌐
Duke University
people.duke.edu › ~ccc14 › sta-663 › FunctionsSolutions.html
Functions are first class objects — Computational Statistics in Python 0.1 documentation
In Python, functions behave like any other object, such as an int or a list. That means that you can use functions as arguments to other functions, store functions as dictionary values, or return a function from another function.
🌐
Aknin
tech.blog.aknin.name › 2010 › 07 › 03 › pythons-innards-code-objects
Python’s Innards: Code Objects – NIL: .to write(1) ~ help:about
Functions are higher level creatures that execute code by relying on a lower level primitive, the code object, but adding more functionality on top of that (in other words, every function has precisely one code object directly associated with it, this is the function’s __code__ attribute, or f_code in Python 2.x).
Top answer
1 of 2
46

You are looking for the __call__ method. Function objects have that method:

>>> def foo(): pass
... 
>>> foo.__call__
<method-wrapper '__call__' of function object at 0x106aafd70>

Not that the Python interpreter loop actually makes use of that method when encountering a Python function object; optimisations in the implementation jump straight to the contained bytecode in most cases.

But you can use that on your own custom class:

class Callable(object):
    def __init__(self, name):
        self.name = name

    def __call__(self, greeting):
        return '{}, {}!'.format(greeting, self.name)

Demo:

>>> class Callable(object):
...     def __init__(self, name):
...         self.name = name
...     def __call__(self, greeting):
...         return '{}, {}!'.format(greeting, self.name)
... 
>>> Callable('World')('Hello')
'Hello, World!'

Python creates function objects for you when you use a def statement, or you use a lambda expression:

>>> def foo(): pass
... 
>>> foo
<function foo at 0x106aafd70>
>>> lambda: None
<function <lambda> at 0x106d90668>

You can compare this to creating a string or an integer or a list using literal syntax:

listobject = [1, 'two']

The above creates 3 objects without ever calling a type, Python did that all for you based on the syntax used. The same applies to functions.

Creating one yourself can be a little more complex; you need to have a code object and reference to a global namespace, at the very least:

>>> function_type = type(lambda: None)
>>> function_type
<type 'function'>
>>> function_type(foo.__code__, globals(), 'bar')
<function bar at 0x106d906e0>

Here I created a function object by reusing the function type, taking the code object from the foo function; the function type is not a built-in name but the type really does exist and can be obtained by calling type() on an existing function instance.

I also passed in the global namespace of my interpreter, and a name; the latter is an optional argument; the name is otherwise taken from the code object.

2 of 2
8

One simple way to see this is to create a function in the Python interpreter def bar(x): return x + 1 and then use dir(bar) to see the various magic attributes including __class__.

Yes, python functions are full objects.

For another approach, objects are functions if they have a magic __call__() method.

🌐
Python
docs.python.org › dev › c-api › function.html
Function Objects — Python 3.14.0a7 documentation
This is an instance of PyTypeObject ... exposed to Python programmers as types.FunctionType. ... Return true if o is a function object (has type PyFunction_Type). The parameter must not be NULL. This function always succeeds. PyObject *PyFunction_New(PyObject *code, PyObject ...
🌐
Reddit
reddit.com › r/learnpython › understanding custom made functions
r/learnpython on Reddit: Understanding custom made functions
January 18, 2025 -

Hello all. Ive been recently going through the Harvard CS50 Python course, currently on week 2 and have learned a lot! I feel I understand every topic thoroughly as of now... All except for damn functions. Specifically custom functions with the def() command. Recently we had a project to get user input for a time, convert the minutes given to a float value in a 60 minute time frame and output text based on what time the user gives and whether it fits the needed parameter. With the assistance of some videos and the documentation, I was able to solve the problem and I understand 99% of the code used. I'll link it below, but pretty much what I'm not really grasping is the convert function given in this problem, and really all functions in general that call to main. Why is there a time value in the convert function? How does it pertain to main and why could this not be done in main? What's the purpose of the return at the end of the convert function? An ELI5 type explanation on custom functions in general would be greatly appreciated. I feel like I'm so close to enlightenment but my dummy brain doesn't want to grasp this concept lol.

Link to project: https://imgur.com/a/VARI0p2

Top answer
1 of 5
4
They covered functions in the first week of the course. A function defines deferred behavior. Deferred, because the behavior doesn’t occur when you define the function, but later, when you call the function. Deferred behavior is the difference between telling someone how to bake a cake, and telling someone to bake a cake. A function relates input to output. The input of a function is its parameters (if it has any) and the output is its return value, indicated by the use of the return statement.
2 of 5
3
Having a function called main is something of a hangover from other languages, although it is useful in packaging of Python code. You might like to think of a function a bit like the chorus in a song. If you look at the lyrics sheet you will find that after the first verse you get the lyrics of the chorus but after the second verse the text of the chorus isn't repeated, it typically either just assumes you know to sing the chorus again or it explicitly says "chorus". If you want to change the chorus of a song you now only have to change it in one place. In some songs, we change the chorus to feature the name(s) of people at an event. In the chorus lyrics it might say , or host, bride, "groom", etc. This is like the arguments of a function. It is convenient in the chorus to have placeholders that are replaced when sung with whatever is appropriate. The nursery song "Old MacDonald had a farm" could be seen as a more complex version of this. In many programming languages, there is always a function called main (or whatever the default function for that language is called) that gets called automatically when the programme is invoked. Python works differently. When you pass a file of Python code to the Python execution programme, it simple starts reading from the top of the file and executing instructions as encountered (definitions for functions, def and classes, class, aren't executed immediately but are prepared for later use when called upon (a bit like having the chorus appearing first but not being sung until you are instructed to). If you provide Python code with no functions, it just starts being executed from beginning. As your programming gets more complex, you will start to use functions and classes. There are a few good reasons for this: modular programming having a large amount of code can get very confusing splitting it into separate blocks (modules) of code where each module has a clear purpose (e.g. login a used, calculate overtime pay, check stock levels, etc) makes it easier to develop, test, and update code without breaking other things it also makes the overall flow of code easier to understand as the code that is the first to be executed after functions and classes are defined can be written in near plain English (or native language of the programmer), for example: show_menu() select_food() select_toppings() select_drinks() take_payment() place_order() repeated use Just like in a chorus, often in programming, you want to do basically the same thing in many different places, so rather than having multiple copies of basically the same code, each of which then needs to be maintained and tested, having one class or function that can be re-used (which minor changes such as replacing names (data structures) makes it very much easier For example, you might want to check the current temperature of a sensor in some factory automation setup and even if this takes several lines of code, you can write it once and then call sense_temperature(sensor[location]) which can be used to get the temperature from any of several sensors independent use Over time, you might come up with some brilliant functions. Functions that you want to use in other programmes you write. Python lets you use functions written in one programme from another programme using the import command. However, when you import code, it is run. The imported definitions don't do anything until they are called, but any other root or top level code is executed immediately. To avoid this you put ALL code into functions, and it is common to put what would otherwise be your top level code in a function called main (any name can be used). The test if __name__ == "__main__": isn't about a function called main but indicates if the programme code has been run directly, in which case the test will be True or was imported, in which case the test will return False as __name__ will not have been assigned the string "__main__" but instead the name of the file that was imported. Your main function will call other functions as required to do its job. You however, on importing the same file, can make use of any of those functions directly.
🌐
Late
late.am › post › 2012 › 03 › 26 › exploring-python-code-objects.html
Exploring Python Code Objects « late.am
March 26, 2012 - Code objects, then, are Python ... executable code, they are not, by themselves, directly callable. To execute a code object, you must use the exec keyword or eval() function....
🌐
The Python Coding Stack
thepythoncodingstack.com › p › python-functions-first-class-objects
"I'm One of You!" Said the Function to the Other Objects
April 7, 2024 - The value of display_items is a function object–either print or create_menu: ... Note how you call display_items by adding parentheses, just like you'd call a function. The name display_items refers to a function since suprise_print() returns a function. Can you guess what function display_items() returned each of the three times I called it in the code above?
🌐
Medium
medium.com › python-pandemonium › function-as-objects-in-python-d5215e6d1b0d
Functions as Objects in Python. In Python, everything is an object… | by Chaitanya Baweja | Python Pandemonium | Medium
July 19, 2019 - For the rest of the tutorial, we will define an ‘apply’ function which will take as input a list, L and a function, f and apply the function to each element of the list. This example has been taken from the Edx Course 6.00.1.x. ... A place to read and write about all things Python.
Top answer
1 of 3
3

You already extracted the code objects, now all you have to do is to create the functions objects using types.FuncitonType. It accepts:

  1. Code object
  2. Reference to the global module
  3. Name
from types import FunctionType

code_string = """\
def f1(p1, p2, p3):
    print("a{}, b{}, c{}".format(p1, p2, p3))
def f2():
    print("text")
"""

code = compile(code_string, "<string>", "exec")

f1_code_object = code.co_consts[0]
f2_code_object = code.co_consts[1]

f1 = FunctionType(f1_code_object, globals(), "f1")
f2 = FunctionType(f2_code_object, globals(), "f2")
print(f1)
print(f2)
f1(10, 20, 30)
f2()

output:

<function f1 at 0x1042a2980>
<function f2 at 0x1042a2a20>
a10, b20, c30
text
2 of 3
1

All compile() does is translate the Python source code (think contents of *.py files) into a compiled version (think *.pyc files). The source code must be syntactically correct, but need not be valid. In the case of your code_string, this means it has compiled the two def <name>: <body> statements into a binary form, but it has not executed those def statements to actually create the functions.

You need to execute the compiled code object in order to actually execute the def statement that creating the functions.

However, as norok2 mentions, simply executing code in arbitrary strings is a security risk. It can be done somewhat safer by controlling the environment the code is executed in. We can create an environment where the only function that exists is the print function:

code_string = """\
def f1(p1, p2, p3):
    print("a{}, b{}, c{}".format(p1, p2, p3))
def f2():
    print("text")
"""

code = compile(code_string, '<string>', 'exec')

builtins = {
    'print': print,
    }

code_globals = {'__builtins__': builtins}
exec(code, code_globals)

f1 = code_globals['f1']
f_two = code_globals['f2']

f1(1, 2, 3)
f_two()

Now it is much more difficult for the code to break out of the sandbox. For example, if you add import sys inside the code_string, you'll get an NameError: name '__import__' is not defined., and so on.

By careful construction of the available builtins, you can allow as much functionality as needed.

Of course, since we are no longer using the caller's global context to create the definitions, you need to extract the created functions out of the code_globals dictionary, as demonstrated above.


Why compile?

You generally use compile() when you want to execute the resulting code multiple times. That's not the case here. You will likely be executing the code exactly once to create the f1 and f2 functions. (Once created, they can be called many times, but they only need to be created once.) Therefore, we should use exec() instead of compile(), so we don't get (and accidentally keep) a reference to the intermediate code object:

code_string = """\
def f1(p1, p2, p3):
    print("a{}, b{}, c{}".format(p1, p2, p3))
def f2():
    print("text")
"""

builtins = {
    'print': print,
    }

code_globals = {'__builtins__': builtins}
exec(code_string, code_globals)

f1 = code_globals['f1']
f_two = code_globals['f2']

f1(1, 2, 3)
f_two()

Why code.co_consts is fragile

S.B shows how you can directly create functions from code.co_consts[...], and indirectly demonstrates how fragile this is.

Consider the OP's code:

f2 = code.co_consts[2]

compared with S.B's:

f2_code_object = code.co_consts[1]

Apparently, something changed (Python version? An edit to the code_string?) and f2 moved from index 2 to index 1. There is no obvious mapping from the indices in co_consts to the expected function names.

To drive this home, consider this more complex example, which highlights the differences between compiling the Python script and executing it:

from types import FunctionType

code_string = """\
if True == False:
    print("Defining f1...")
    def f1(p1, p2, p3):
        print("a{}, b{}, c{}".format(p1, p2, p3))
else:
    print("Defining alternate f1")
    def f1(p1, p2, p3):
        print("c{}, b{}, a{}".format(p3, p2, p1))
"""

builtins = {
    'print': print,
    }
code_globals = {'__builtins__': builtins}

print("Using compile() and code.co_consts")
code = compile(code_string, '<string>', 'exec')

for idx, item in enumerate(code.co_consts):
    print(f"  .co_consts[{idx}] = {item!r}")

f1 = FunctionType(code.co_consts[3], code_globals) # How do we know it is 3???
f1(1, 2, 3)

print()
print("Using exec():")
code_globals = {'__builtins__': builtins}
exec(code_string, code_globals)

f1 = code_globals['f1']
f1(1, 2, 3)

Now code_string will conditionally define the function f1 based on the execution of the code.

Output:

Using compile() and code.co_consts
  .co_consts[0] = True
  .co_consts[1] = False
  .co_consts[2] = 'Defining f1...'
  .co_consts[3] = <code object f1 at 0x000001A3B567FA30, file "<string>", line 3>
  .co_consts[4] = 'Defining alternate f1'
  .co_consts[5] = <code object f1 at 0x000001A3B56C8330, file "<string>", line 7>
  .co_consts[6] = None
a1, b2, c3

Using exec():
Defining alternate f1
c3, b2, a1

Note that:

  • compile()
    • created two different code object f1 entities,
    • does not execute either print() statement.
  • exec()
    • actually evaluates the condition in the if statement,
    • executes the print() statement in one code path,
    • defines the function "f1" from that code path only.
🌐
Programiz
programiz.com › python-programming › methods › built-in › object
Python object()
The object() function returns a featureless object. test = object() print(type(test)) print(dir(test)) ... <‍class 'object'‍> ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', ...