Related Articles

Related Articles

How to clone a method code in Python?
  • Last Updated : 03 Jun, 2020

With the help of methodName.__code__.replace() method, we can clone the code of builtin method as well as any other defined method and we can also fix the positional only arguments in any of the cloned method code by using methodName.__code__.replace() method.

Syntax : methodName.__code__.replace()

Return : Return the object of new cloned method with few positional only arguments.

Note :
To run the programs given below you have to install the latest version of Python i.e. Python 3.8.2 otherwise it will show the error like this.

AttributeError: ‘code’ object has no attribute ‘replace’.

Example #1 :
In this example we can see that by using methodName.__code__.replace() method, we are able to clone the code of builtin methods as well as any defined method with the help of this method.



filter_none

edit
close

play_arrow

link
brightness_4
code

from statistics import median
  
# Using methodName.__code__.replace() method
median.__code__ = median.__code__.replace(co_posonlyargcount = 1)
  
print(median([1, 2, 3]))

chevron_right


Output :

2

Example #2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

def multiply(a, b):
    return a * b
  
# Using methodName.__code__.replace(co_posonlyargcount = 1) method
multiply.__code__ = multiply.__code__.replace(co_posonlyargcount = 2)
  
print(multiply(5, 6))

chevron_right


Output :

30

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :