using inspect

E

Ethan Furman

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?

~Ethan~
 
S

Steven D'Aprano

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top