Runtime Inspection Methods
code.replace()
Create a new code object with selected fields replaced by keyword arguments, leaving the original unchanged. Added in 3.8. Do not construct arbitrary invalid bytecode; metadata changes can affect debugging.
Formal Syntax & Structure
python syntaxpython
code.replace(**changes)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| changes | keyword arguments | Selected valid code object fields, such as co_filename; unspecified fields retain their original values. |
Return Value
types.CodeType
Result of the inspection method.
Working Example
Example Snippetpython
def f(): return 7code = f.__code__new = code.replace(co_filename='<demo>')print((new.co_filename,new is code))