When is a module imported from the standard library?

Skip Montanaro skip at pobox.com
Wed Aug 22 18:41:49 EDT 2001


    cary> is simplest if you only want to know about the os module.  To get
    cary> the location of any module do this:

    cary> mod = os
    cary> os.path.dirname(eval(mod.__name__).__file__)

Why the eval?  Why not simply

    os.path.dirname(mod.__file__)

?  Also, note from the subject the question was how to tell if a module was
imported from the standard library.  The os module is almost certainly going
to be found there.  If not, the programmer deserves whatever they have
coming to them (and hopefully knows to expect it).

FWIW, On typical Unix installs, there will be at least three locations that
contain stuff delivered with Python:

    os.path.dirname(os.__file__)
    os.path.dirname(os.__file__) + "/lib-dynload"
    os.oath.dirname(os.__file__) + "/plat-" + sys.platform

All modules in those directories should have a valid __file__ attribute.  In
addition, modules that are statically linked into the interpreter will not
have a __file__ attribute, so you can't really tell if they are part of the
core or a third-party extension that was statically linked into the
interpreter. 

YMMV for non-Unix platforms.

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list