tags:

views:

40

answers:

1

Python beginner here, so I apologize if this question has a simple answer. (I hope it does.)

I am working on a python module--a plugin for a larger program. I'm trying to develop the module using the Eclipse IDE (with pydev), which means I need to be able to run this module stand-alone, i.e. not as a plugin from the larger program.

I've actually sorted out a lot of the hairy details of this on my own, much of it involving creating a sort of "harness" that launches the plugin from my IDE in a way that simulates (from the plugin's perspective) being launched from within its real operating environment.

But one thing eludes me. When the module is run from within it's "real" environment, it somehow has a certain name (call it "Bob") already defined in its dir() results. When I run it in my own environment, "Bob" doesn't appear in dir() unless I load it manually.

Naturally, if I wrote code to load "Bob" manually just so that the plugin will work in my IDE, that interferes with the plugin when it is running "for real". What I need help with is: how do I get my plugin to start up (via my launching harness) with "Bob" already loaded?

Naively, I'm kind of hoping to somehow be able to "force" the plugin to import "Bob" somehow, without actually having to add "import Bob" to the plugin itself. But I'm open to suggestions on a better way...?

+2  A: 

Presumably, when you run it "stand-alone" under Eclipse (or "stand-alone" without Eclipse, for that matter, just as "python foobar.py" at a shell prompt), your module's __name__ global variable has the value of '__main__' (if the module gets imported, instead, that global variable's value will be 'foobar' -- or however the module's named).

So, just do

if __name__ == '__main__':
    import Bob

and you can have Bob imported when your module is run stand-alone, without any ill-effect when your module is instead getting imported.

Alex Martelli
I agree. This statement should be part of your harness.
inspectorG4dget
Ah, yes this works. Thank you. Out of curiosity, do either of you guys know how the "real" program (which calls my plugin) manages to add a name to the plugin's dir() without explicitly importing it? (I assume that name must correspond to a module, variable, or class...)
Xanatos
@Xanatos, `import foobar; foobar.Bar = 'zapzap'` will do it (generally not best practice, but definitely not hard). "Explicitly" is no big deal -- no matter how the import occurrs (`__import__`, whatever), the module object end up as `sys.modules['foobar']` so it could always be affected in that way.
Alex Martelli
@Alex: Ah yes that must be how the real program is doing it. Thanks again for the help.
Xanatos