Running external module and accessing the created objects

Dave Angel davea at
Tue Mar 12 03:11:24 CET 2013

On 03/11/2013 09:23 PM, Kene Meniru wrote:
> Dave Angel wrote:
>> On 03/11/2013 07:57 PM, Kene Meniru wrote:
>> I hope you're just kidding.  execfile() and exec() are two of the most
>> dangerous mechanisms around.  import or __import__() would be much
>> better, as long as your user hasn't already run as his script.
> It does what I want. Security is another issue and I understand but can't
> help it until I find another solution.
> import does not do what I want.
> How does __import__() work and what do you mean "as long as your user hasn't
> already run as his script."?

The __import__() function is defined

appname = "myapp"
usermodule = __import__(appname, globals(), locals(), [], -1)

And now you can use usermodule as though you had imported it in the 
usual way.

As for my other caveat, I've said it before in this thread.  Make sure 
you don't ever load a module by more than one name, or you'll end up 
with a mess.  And that includes the original script, which is loaded by 
the name '__main__'

You also should avoid any circular import, as it can be very tricky to 
deal with them.

As I said earlier in the thread:

 >>>> For example the __import__() function can import a module that you
 >>>> don't know the name of ahead of time.  It's not often the right
 >>>> answer, though, so I hesitate to suggest it.
 >>>> For another example, if you import a module by two different names,
 >>>> or if you import the "module" that is your starting script, then
 >>>> you can end up with two instances of such a module, with all sorts
 >>>> of negative implications about global data or class attributes
 >>>> stored in that module, or even more subtle problems.
 >>>> For a final example, having a circular import tree can cause
 >>>> problems if any of those imports have any global code (like class
 >>>> initialization, defining constants, etc.).  It's generally much
 >>>> better to define a strict hierarchy of who imports whom.


More information about the Python-list mailing list