[Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ?

Steven D'Aprano steve at pearwood.info
Sun Feb 14 16:37:37 CET 2010


On Sun, 14 Feb 2010 10:33:09 pm patrice laporte wrote:

> I got a class that takes a file name in its  __init__ method (it
> could be elsewhere, but why not here ?). Then, somewhere in that
> class, a method will do something with that file  name, such as "try
> to open that file".
>
> If the file do esn't exist, bing ! I got an exception "I/O Error n°2
> : file doesn't exist".

Are you sure? What version of Python are you using? I get a completely 
different error message:

>>> open("no such file.txt", "r")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'no such file.txt'

Note carefully that the exception shows you the file name.


> That's nice, I of course catch this exception, but it's not enough 
> for the user : What file are we talking about ?  And how to tell the
> user  what is that file, and make him understand  he tell the app to
> use a file that doesn't exist ?


>>> try:
...     open("no such file.txt", "r")
... except IOError, e:
...     pass
...
>>> e.filename
'no such file.txt'



> And this is not enough for developer : where that error happened ?
> what class ? what method ?

All these things are displayed by the default traceback mechanism.



-- 
Steven D'Aprano


More information about the Tutor mailing list