[Python-Dev] PEP: __source__ proposal

Nick Coghlan ncoghlan at iinet.net.au
Sat Dec 4 15:29:27 CET 2004

[Resend, since a minor brain explosion caused me to send this to c.l.p instead 
of python-dev]

Stelios Xanthakis wrote:
> It appears that there are the 'module people' who
> find this feature irrelevant. Indeed. If we are interested
> in distributing modules and increasing the number of
> people who use python programs,then  __source__ is redundant.
> OTOH, programming python is easy and fun and I think
> the proposed feature will make it even more fun and it
> aims in increasing the number of people who program
> python for their every day tasks. It'd be interesting to
> hear if the developers of IDLE/ipython/etc could use this.

The feedback here (and the initial response on py-dev a while back) suggests to
me that you should look at making this a feature of the interactive mode.
Something that affects both Python's main interactive shell, plus the relevant
class in the standard library (CommandInterpreter or whatever it is called).

A late-night-train-of-thought example of what might be handy is below - keep in
mind that I haven't looked at what enhanced Python shells like IPython can do,
so it may be there are tools out there that do something like this already. It
would be handy to have a standard library module that supported "on-the-fly"
editing, though (this capability would then be available to anyone embedding
Python as a scripting engine).

>>>import source
>>>class bob:
...  def mary():
...    pass
...  def tim():
...    print 'Tim'
>>>print bob.__source__
class bob:
   def mary():
   def tim():
     print 'Tim'

>>>print bob.mary.__source__
def mary():

>>> source.edit(bob.mary)
bob.mary(1)>def mary(text): # [1]
bob.mary(2)>  print "Mary:", text
>>> source.edit(bob.tim)
Commands: \help \cancel \save \deleteline
>>>print bob.__source__
"class bob:
   def mary(text):
     print "Mary:", text
   def tim():
     print 'Tim'
>>> bob().mary("Hi!")
Mary: Hi!

The basic ideas of the above:

"import source" triggers the storage of the __source__ attributes (e.g. via
installation of appropriate hooks in the class and function definition process)

The 'edit' function is then able to take advantage of the stored source code to
present each line of the original source for modification (e.g. to fix a minor
bug in one function of a class definition). When the 'edit' is complete, it can
be saved or cancelled.

1. The feature mentioned in the last paragraph is hard to show in the expected
output :)

Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia

More information about the Python-Dev mailing list