using inspect

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Nov 12 00:05:57 EST 2009


On Wed, 11 Nov 2009 18:15:22 -0800, Ethan Furman wrote:

> Greetings!
> 
> How wise is it to base code on inspect?  Specifically on things like
> live frames on the stack and whatnot.  It occurs to me that this is
> leaning towards implementation details, and away from pure, pristine
> Python.
> 
> As an example, I have this routine in a module I'm working on:
> 
> def _get_module():
>      "get the calling module -- should be the config'ed module" target =
>      os.path.splitext(inspect.stack()[2][1])[0]
>      target = __import__(target)
>      return target
> 
> How brittle is this technique?


Download and install PyPy, CLPython, IronPython and Jython and see how 
many it breaks on :)


I think it's a brittle technique because it is creating a dependency 
where there shouldn't be one. What happens if somebody runs your module 
directly? It might not need to do anything sensible, but it shouldn't 
fail merely because there's no calling module.

But I don't think it's inherently dangerous. It's a bit hacky, well, 
probably a lot hacky, but it doesn't seem to use anything specifically 
documented as implementation specific:

http://docs.python.org/library/inspect.html#inspect.stack




-- 
Steven



More information about the Python-list mailing list