On Tue, Apr 6, 2021 at 5:36 AM Rob Cliffe via Python-list <python-list@python.org> wrote: > > > > On 05/04/2021 18:33, Chris Angelico wrote: > > > > Firstly, anything with any variable at all can involve a lookup, which > > can trigger arbitrary code (so "variables which do not occur on the > > LHS" is not sufficient). > Interesting. I was going to ask: How could you make a variable lookup > trigger arbitrary code? > Then I saw your post in the "Yield after the return in Python function" > thread. (Took me a while to understand it.) So I ask: > Can you make a variable lookup trigger arbitrary code, other than in > code passed to eval/exec/compile?
Hmm. When you're defining a class, the metaclass can set the namespace dictionary, does that count? class Wat(dict): def __getitem__(self, name): print("HEY! You're looking for %r!" % name) return 42 def __setitem__(self, name, value): print("Okay, I'm setting %r to %r." % (name, value)) # I'm totally not. class WutFace(type): @classmethod def __prepare__(cls, name, bases): return Wat() class Gotcha(metaclass=WutFace): a = b + 1 But for top-level code in a module, or for function locals, I'm not sure of any way to do this. It might be possible to mess with sys.modules[__name__] but the __dict__ attribute can't be changed, so you might need to first subclass the module. In general, though, even if you can't find an example of how to do it, you have to assume that it could happen somewhere, some time. (It might also be possible to mess with the builtins module, which would effectively catch any name lookups that aren't resolved locally or at module level. Again, not sure if that would count.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list