Adding a __filename__ predefined attribute to 2.5?

Alex Martelli aleax at
Wed Oct 12 23:39:02 CEST 2005

Rune Strand <rune.strand at> wrote:

> > those modules are already imported when Python gets to your code, so
> > the only "overhead" you're saving is a little typing.
> I don't understand this. Could you please elaborate?  - if sys or os
> are not imported for any other causes how are they already imported?

The "other causes" are always present, since these modules include
functionality Python always needs -- a fact that is no big secret,
either.  For example: you know (I assume and hope) that Python's import
statement finds files to import along directories (and zipfiles) listed
in sys.path -- so how do you think 'sys' itself can possibly get
'imported' in the first place, since the import mechanism depends on one
of sys's attributes...?  Answer: sys is a built-in module, compiled into
the Python interpreter itself.  There are several, see
sys.builtin_file_names for a list.  'os' is a slightly different case --
it's not built-in, but gets imported anyway during startup because other
modules need it anyway.  In my build of Python 2.4.1, there are 16
built-in modules, and 9 others that aren't built-in but get imported at
startup -- check sys.modules on your version for the total number of
modules that are in memory by the time any code of yours runs.  (This is
with -S to inhibit Python from reading the module, otherwise you
might get more... but never, I believe, could you get fewer).

> Maybe I'm wrong here, and accessing the filesystem and reading the
> module into memory represents no cost. My mistake, in that case.

Your mistake is due to a different case: the filesystem access and
reading have ALREADY happened (for os; for sys, as I explained, the
mechanism is different).  Therefore, an import does NO such access and
reading -- it just gets the module object from (e.g.) sys.modules['os'].

> > wow.  that's one lousy optimization...
> > here's a *shorter* piece of code, which is also readable and portable, and
> > a lot easier to type on most keyboards:
> >   import os
> >  __filename__ = os.path.basename(__file__)
> It may be lousy, but it requires no imports. And, as I said in the

The point is that there's no substantial advantage to "requiring no
imports".  Python, if anything, already has too many built-ins -- once
backwards compatibility can be broken (i.e., in 3.0), many of them
should be moved to standard library modules, "requiring imports" (which
are cheap operations anyway).  The desire for MORE built-ins with no
real advantage (since "requiring no imports" ISN'T a true advantage) is
definitely misplaced.


More information about the Python-list mailing list