Why self?

Fernando Pérez fperez528 at yahoo.com
Wed Jul 10 16:48:57 EDT 2002


David LeBlanc wrote:

> Louis;
> 
> I think he was proposing an idea. I don't believe you can import from self,
> and i'm almost positive that "to ... export" isn't part of Python.
> 
>> In article <slrnaiov1i.9ea.huaiyu at gauss.almadan.ibm.com>, Huaiyu Zhu
>> <huaiyu at gauss.almadan.ibm.com> wrote:
>>
>> > The Pythonic way to use namespace is :-)
>> >
>> > from self import x, y, z, a, tseries
>> > y= x**2 * t/z + a * FFT(tseries)
>> > to self export y

True, but it would actually be pretty simple to write a pair of helper 
functions to do just that. In fact I have one for the second part which I use 
a fair bit:

def setattr_list(obj,alist,nspace = None):
    """Set a list of attributes for an object taken from a namespace.

    setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
    alist with their values taken from nspace, which must be a dict (something
    like locals() will often do) If nspace isn't given, locals() of the
    *caller* is used, so in most cases you can omit it.

    Note that alist can be given as a string, which will be automatically
    split into a list on whitespace. If given as a list, it must be a list of
    *strings* (the variable names themselves), not of variables."""

    # this grabs the local variables from the *previous* call frame -- that is
    # the locals from the function that called setattr_list().
    # - snipped from weave.inline()
    if nspace is None:
        call_frame = sys._getframe().f_back
        nspace = call_frame.f_locals

    if type(alist) in StringTypes:
        alist = alist.split()
    for attr in alist:
        val = nspace[attr]
        setattr(obj,attr,val)

I can then do:
...
seattr_list(self,'x y z a b c')
or 
seattr_list(self,['x','y','z','a','b','c'])

at the end of a method to replenish my self namespace. 

cheers,

f.

ps. I also have a little companion getattr_list(). I'm not sure if it's 
possible to inject back variables into the frame of a caller though, as I 
seem to recall that locals() is to be considered read-only.




More information about the Python-list mailing list