__getattr__ for global namespace?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu May 4 23:56:58 CEST 2006


Harold Fellermann a écrit :
> Hi,
> 
> I am writing an application that initializes the global namespace, and
> afterwards, leaves the user with the python prompt. Now, I want to
> catch NameErrors in user input like e.g.
> 
> 
>>>>some_name
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'some_name' is not defined
> 
> For classes, there are the __getattr__ and __getattribute__ functions.
> I wonder if there is some related function for (failed) global
> attribute
> lookup that is invoked with name as its argument instead.
> 
> I consulted the docs, but could not find anything. Any ideas?

http://docs.python.org/lib/module-sys.html

"""
excepthook(  	type, value, traceback)
     This function prints out a given traceback and exception to sys.stderr.

     When an exception is raised and uncaught, the interpreter calls 
sys.excepthook with three arguments, the exception class, exception 
instance, and a traceback object. In an interactive session this happens 
just before control is returned to the prompt; in a Python program this 
happens just before the program exits. The handling of such top-level 
exceptions can be customized by assigning another three-argument 
function to sys.excepthook.
"""

>>> import sys
>>> def myhook(type, value, tb):
...     print "got ", type, value, tb
...
...
>>> sys.excepthook = myhook
>>> toto
got  exceptions.NameError name 'toto' is not defined <traceback object 
at 0x40416694>
>>>

HTH




More information about the Python-list mailing list