How to override inline getattr in Python?

I know how to override the getattr () object to handle function calls to the undefined object. However, I would like to achieve the same behavior for the getattr () built-in function. For example, consider this code:

   call_some_undefined_function()

This usually just causes an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'call_some_undefined_function' is not defined

I want to override getattr () to intercept the call to "call_some_undefined_function ()" and figure out what to do.

Is it possible?

+3
source share
2 answers

I can only think about how to do this by calling eval.

class Global(dict):
    def undefined(self, *args, **kargs):
        return u'ran undefined'

    def __getitem__(self, key):
        if dict.has_key(self, key):
            return dict.__getitem__(self, key)
        return self.undefined

src = """
def foo():
    return u'ran foo'

print foo()
print callme(1,2)
"""

code = compile(src, '<no file>', 'exec')

globals = Global()
eval(code, globals)

Above outputs

ran foo
ran undefined
+2
source

, . , , Python, python:

import sys
import re

def nameErrorHandler(type, value, traceback):
    if not isinstance(value, NameError):
        # Let the normal error handler handle this:
        nameErrorHandler.originalExceptHookFunction(type, value, traceback)
    name = re.search(r"'(\S+)'", value.message).group(1)

    # At this point we know that there was an attempt to use name
    # which ended up not being defined anywhere.
    # Handle this however you want...

nameErrorHandler.originalExceptHookFunction = sys.excepthook
sys.excepthook = nameErrorHandler

, , undefined... OP , , , - .

0

Source: https://habr.com/ru/post/1750331/


All Articles