pythonpython-3.xname-manglingdynamic-class-creation

python: name mangling in a dynamically created class


I want to do something like this

def make_class(name : str)->type:
    class Ret:
       __name__ = name
       def __init__(self):
           self.__x = 0
    return Ret

A = make_class('A')
a = A()
assert a._A__x == 0

Basically, what I want is to create a type so that it mangles its members according to a dynamic identifier, but the above example doesn't work. Metaclasses don't either.

The only solutions I can think of are:

exec the entire class definition

exec("""
class {}:
    def __init__(self):
        self.__x = 0
""".format(name))

or set the attribute via getattr

class Ret:
    def __init__(self):
        setattr(self,'_'+name+"__x",0)

but both of them are unattractive for various reasons, is there a right way to do this?


Solution

  • Python name mangling is fundamentally static. It is performed at bytecode compilation time, before your function's name argument is available. To invoke this mechanism dynamically, you would have to compile code dynamically, which means you would have to use exec or something like it.