import x as y

Thomas Bellman bellman at lysator.liu.se
Tue Oct 31 16:54:35 EST 2000


grante at visi.com (Grant Edwards) writes:

> In article <mVEL5.145182$g6.66741488 at news2.rdc2.tx.home.com>, Rainer Deyke wrote:

>> On a related note, I want the following to work:
>> 
>> l = [0]
>> def l[0]():
>>   pass

> Well, it doesn't.

> Perhaps you can explain a little further _why_ you want that to
> work and perhaps we can suggest an alternative means to that end.

I'm not Rainer Deyke, but I can at least think of situations
where that would be convenient.  If you are making a table of
functions, you have to do:

    def f0(...):
	...
    def f1(...):
	...
    ...
    def f4711(...):
	...

    table = [ f0, f1, ..., f4711 ]

Instead, you could do:

    def table[0](...):
	...
    def table[1](...):
	...
    ...
    def table[4711](...):
	...

Another similar situation would be to add methods to a class
after it is definied:

    class C:
	def m1(self, ...):
	    ...

    def C.m2(self, ...):
	...

That one is probably not very useful in "real" use, but when
running Python interactively and testing things, it has happened
that I found out that I wanted to add or replace methods in my
classes after they are created.  I then have to do

    >>> def m2(self, ...):
    ...     ...
    >>> C.m2 = m2

On a related note, one thing I sometimes would like to do, is to
change the "active" module in interactive mode from __main__ to
some other module, for the same reasons.  I.e, I have imported a
module, and for testing out things, I want to add or replace
functions or modules in it.  What I want to do is:

    >>> import spam
    >>> def parrot(x):
    ...     print spam.viking(x+3)
    >>> parrot(17)
    Traceback (innermost last):
      File "spam.py", line 311 in viking
        t = lognship(17)
    NameError: lognship

    # Oh, I misspelled longship
    >>> set_current_module(spam)
    >>> def viking(i):
    ...     t = longship(17)
    ...     return t+i
    >>> set_current_module(__main__)
    >>> parrot(17)
    4711

Of course, I need to change the file spam.py too, but for
experimentation it would be convenient to be able to do something
like that.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Adde parvum parvo magnus acervus erit"       ! bellman @ lysator.liu.se
          (From The Mythical Man-Month)       ! Make Love -- Nicht Wahr!



More information about the Python-list mailing list