
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Code Objects
Code objects are a low-level detail of the CPython implementation. Each one represents a chunk of executable code that hasn’t yet been bound into a function. Though code objects represent some piece of executable code, they are not, by themselves, directly callable. To execute a code object, you must use the exec keyword.
In the below example we see how the code objects are created for a given piece of code and what are the various attributes associated with hat code object.
Example
code_str = """ print("Hello Code Objects") """ # Create the code object code_obj = compile(code_str, '<string>', 'exec') # get the code object print(code_obj) #Attributes of code object print(dir(code_obj)) # The filename print(code_obj.co_filename) # The first chunk of raw bytecode print(code_obj.co_code) #The variable Names print(code_obj.co_varnames)
Output
Running the above code gives us the following result −
<code object <module> at 0x000001D80557EF50, file "<string>", line 2> ['__class__', '__delattr__', '__dir__', '__doc__', ……., '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', …..,posonlyargcount', 'co_stacksize', 'co_varnames', 'replace'] <string> b'e\x00d\x00\x83\x01\x01\x00d\x01S\x00' ()
- Related Articles
- How to retrieve source code from Python objects?
- How to access Python objects within objects in Python?
- Writing Efficient Python Code
- How will you Convert MATLAB Code into Python Code?
- Are Python functions objects?
- Timer objects in Python
- Barrier Objects in Python
- File Objects in Python?
- Packaging and Publishing Python code?
- Optimization Tips for Python Code?
- Morse Code Translator in Python
- How do you compare Python objects with .NET objects?
- How we can convert Python objects into JSON objects?
- Inspect live objects in Python
- Creating Instance Objects in Python

Advertisements