module.__self__ and "on import" conventions

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Wed, 15 Dec 1993 17:27:24 -0500

After running into a desire for a module.__self__ several times since I
first brought it up, I have added the following line to moduleobject.c
( function newmoduleobject() ):

<
< dict2insert( m->md_dict, newstringobject("__self__"), m );
<

The module's __name__ is usually what I require.
That can now be accessed from within the module by:
getattr( __self__, '__name__' )

But '__self__', itself, has to be an entry in the module's __dict__,
rather than an attribute 'cause you can't use gettattr unless you
have a reference to an object whose attributes you get.

(1) DO I need to have an INCREF( m ) along with that line above ?

(2) Since Guido wasn't too convinced of the need for a self reference,
I'll entertain suggestions for other methods to solve the same
problem:

I have gotten used to several of my modules doing some action
when run as a script, vs when imported as a module. Typically,
this is either a test of the module, or an application that was
the main reason for writing it ( although I often end up using
the functions in that module for other things, later. ).

Frequently, the last piece of code in the module is somthing like:

import sys
if sys.argv[1:] :
do_something( sys.argv[1:] )

- or perhaps -

for arg in sys.argv[1:]:
do_something( arg )

This distinguished between running: 'module.py args... ' from the
shell, versus typing 'import module' from interactive python, but
it get's confused when imported from another module that tries to
do the exact same thing.

So, my solution here was to check if sys.argv[0] contains the
module name in it's basename. ( Which, to avoid hardwiring the
module's filename into the module, requires a way to access
module.__name__ from within module.

(3) Does anyone have another way of getting the module name ?

(4) Does anyone have another suggestion of a different sys.argv
processing convention that would bypass my need for this trick ?
Anyone else have any typical default actions on import ?
( whether or not they solve this particular problem. )

(5) I'm still not completely wild about sticking "__self__" in
every module's __dict__. Other ideas ? Maybe __self__ should
be a special symbol to the parser, that is evaluated in
context to a particular value. ( As in some other OO languages,
where 'self' is a reserved word, rather than a conventional name. )

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics