1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Dynamic/runtime method creation (code generation) in Python

Discussão em 'Python' iniciado por Stack, Maio 31, 2025.

  1. Stack

    Stack Membro Participativo

    I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring.

    I came up with a solution combining exec and setattr, here's a dummy example:

    class Viking(object):
    def __init__(self):
    code = '''
    def dynamo(self, arg):
    """ dynamo's a dynamic method!
    """
    self.weight += 1
    return arg * self.weight
    '''
    self.weight = 50

    d = {}
    exec code.strip() in d
    setattr(self.__class__, 'dynamo', d['dynamo'])


    if __name__ == "__main__":
    v = Viking()
    print v.dynamo(10)
    print v.dynamo(10)
    print v.dynamo.__doc__


    Is there a better / safer / more idiomatic way of achieving the same result?

    Continue reading...

Compartilhe esta Página