Why can't use eval() function with a private variable?

Viewed 62

I wonder why it's not possible to use eval() function on the private attributes.

class A:
    def __init__(self):
        __private = 5
        print(__private + 2)  # Prints '7'
        print(eval('__private + 2'))  # NameError: name '__private' is not defined

A()
1 Answers

It's related to the name mangling, see the documentation:

Notice that code passed to exec() or eval() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing __dict__ directly.

So, to properly use a private variable in eval(), it has to be passed in a mangled form, e.g. print(eval('_A__private + 2'))

Related