
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ()
Advertisements