3

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?

1
  • 1
    Note, exec(...) is how namedtuple is actually implemented, so... Commented May 17, 2018 at 21:17

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.