[C++-sig] Calling import() multiple times for the same module

David Abrahams dave at boostpro.com
Mon Oct 27 22:43:36 CET 2008


on Mon Oct 27 2008, "Robert Dailey" <rcdailey-AT-gmail.com> wrote:

> On Fri, Oct 24, 2008 at 1:07 PM, Stefan Seefeld <seefeld at sympatico.ca> wrote:
>
>     Robert Dailey wrote:
>    
>         Hi,
>        
>         What happens if I do the following?
>        
>         using namespace boost::python;
>        
>         import( "__main__" ).attr( "new_global" ) = 40.0f;
>         import( "__main__" ).attr( "another_global" ) = 100.0f:
>
>         My main concern here is performance. I'm wondering if each call to
>         import() results in a disk query for the script in question and loads it
>         from there. I'm also wondering if the second import() above will simply
>         read from a memory cache or something.
>
>     As the above code is only a wrapper around the Python runtime, you are really
>     asking about how Python handles repeated 'import' calls. I'm pretty sure
>     importing a module while it is already imported will do (almost) nothing.
>     However, I'm not sure whether a module is actually unloaded as soon as the last
>     reference goes away (such as after the first line above is completed), so I
>     can't give a definite answer.
>    
>     I'm sure you'll get better answers when asking on a Python forum directly.
>
> I posted about this on the Python mailing list but I'm receiving no responses :(

Python keeps a dictionary in sys.modules that maps module names to
module objects.  Import looks there first and doesn't hit the filesystem
if it finds anything.

-- 
Dave Abrahams
BoostPro Computing
http://www.boostpro.com


More information about the Cplusplus-sig mailing list