0

think I've stumbled upon a weird bug in python and it goes like this:

class Foo:
def __init__(self):
    print(eval('self.example(lambda: self.pass_me("example"))'))

def example(self, func):
    return func()

def pass_me(self, arg1):
    print(arg1)

running this class will return a: NameError: name 'self' is not defined.

However running it without the eval will work perfectly:

class Foo:
def __init__(self):
    print(self.example(lambda: self.pass_me("example")))

def example(self, func):
    return func()

def pass_me(self, arg1):
    print(arg1)

anyone know if this is actually a bug or if I'm overlooking something?

and since bug discussions tend to diverge into chaos be polite in the answers we are all here to learn

Code Pal
  • 68
  • 8
  • 1
    `eval` is not evaluated within a context of current function. By default it only has access to global namespace. Also, don't use `eval`. – matszwecja Sep 28 '22 at 13:15
  • Like @matszwecja mentioned, you're missing the scope argument to `eval`. So, `print(eval('self.example(lambda: self.pass_me("example"))', locals()))`. But to reiterate, you probably shouldn't do this in practice. – Axe319 Sep 28 '22 at 13:22
  • @matszwecja wait so eval cant read self cause its evaluated outside the class? fair enough but we can agree that's an extremely non intuitive implementation. Nothing else (that comes to mind) works like that in python. Also need eval to run custom pystray commands – Code Pal Sep 28 '22 at 13:33
  • Not much else in Python executes arbitrary code from a string, so that's kinda moot point. – matszwecja Sep 28 '22 at 13:39

0 Answers0