How to dynamically add static methods to a class using exec?

CiaranWelsh

I am trying to dynamically create methods in a class but I'm running into TypeErrors. I suspect that the issue is that I have not bound the method to the class meaning I cannot call it. However, my efforts with types.MethodType have failed. Here's an abstract example:

class cls:

    def __init__(self):
        pass

    def method_adder(self):
        """
        I want to add a method to this class from
        a string
        :return:
        """
        string_func = "@staticmethod\n"
        string_func += "def dynamic_method():"
        string_func += "    return 'I am a dynamically created string to be a new method'"

        exec(string_func, self.__dict__)


c = cls()
print(c)        

Outputs:

<__main__.cls object at 0x7fae0aa08e10>

Then

c.method_adder()
meth = c.dynamic_method
print(meth)     

produces:

<staticmethod object at 0x7f02375ce748>

but actually using the method:

print(meth())   

raises

TypeError: 'staticmethod' object is not callable

Update

I've switched to a 3.7 env as suggested in the comments. I still get the same error but when I remove the @staticmethod decorator the code works as intended. I could probably work with this, but out of curiosity, any idea how to get the code working with a static method?

SteveJ

I was able to get the following to work -- by moving 'setattr' into the exec statement.

class mycls:

    def method_adder(self):
        exec("""
@staticmethod
def f():
    print ('I am a dynamically created string to be a new method')
setattr(mycls, 'df', f)
            """)

c = mycls()
c.method_adder()
mycls.df()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to add property to a class dynamically?

using static class methods in another class in typescript

Is it possible to grab a static class dynamically using enum?

How to add methods dynamically to Vue component

How to dynamically add class in react?

Add methods dynamically inside a class

How to find private static methods in static class using reflection?

How to add class to SVGRect created dynamically using JavaScript?

How to add a class attribute dynamically?

How to add dynamically a class with Thymeleaf?

How to add objects to an array by using their class name, then calling any of their methods?

How to synchronize two static methods without using the class level lock

How to dynamically add class methods to Rails Models using module

Add class dynamically using jquery

OO design pattern: How to add methods dynamically?

How to add a class to a div dynamically using JavaScript or Jquery?

How to add class dynamically inside a loop using PHP

How to add class dynamically inside a loop using asp

how to dynamically generate methods for proxy class?

How to dynamically add methods to a class?

How to make class methods dynamically using instance variable value

how to add a class dynamically?

Dynamically add accessor methods in Laravel Model Class

Add methods to class dynamically when they are called

Typescript how to dynamically access methods of a class using variables as

How to reference the class and static properties dynamically from static methods in PowerShell?

How to add IConfiguration into a static class

Add methods to class dynamically with types?

Dynamically add methods to a python class