Anonymus functions revisited : tuple actions

Ron radam2 at tampabay.rr.com
Thu Mar 24 23:13:25 CET 2005


On Thu, 24 Mar 2005 12:07:44 -0500, "George Sakkis"
<gsakkis at rutgers.edu> wrote:

>"Kay Schluehr" <kay.schluehr at gmx.net> wrote:
>> [snipped]
>>
>> Wouldn't it be fun to use in Python?
>>
>> Only drawback: does not look like executable pseudo-code anymore :(
>>
>>
>> Regards Kay
>
>I don't know if it would be fun, but it certainly doesn't look accessible to mere mortals :-) I'm
>not sure if the mind boggling is more due to the syntax with the '->' and all or the semantics, but
>it goes in the oppposite direction from my initial proposal (having defaults in for loops) with
>respect to readability.
>
>Regards,
>George
>

Hi George, I think I got the default variable functions working now.

    if isa('name'): do something

Checks locals, globals, and builtins for the varable name.

    variable = ifno('name', object)

Sets a variable name to an object if it does not exist, or sets it to
the 'variable name's object if it does.  (The target doesn't have to
match.) 

They are slower than try/except, but can be used in expressions. Like:

x,y,z = x,y, ifno('z',0) 


#---Here's the code---------------------

import sys

def isa(v):
    """
    Check if a varable exists in the current 
    (parent to this function), global, or 
    builtin name spaces.
    
    use: bool = isa( str )
         returns True or False    
    """
    plocals = sys._getframe(1).f_locals
    if plocals.has_key(v) or globals().has_key(v) or \
                   __builtins__.locals().has_key(v):
        return True
    return False


def ifno(v, obj=None):
    """
    Check if a varable does not exists, return a
    default value, otherwise return the varable obj.

    use: obj = ifno( str [,obj=None] )
         if str exist, returns str's object
         if str does not exist, returns specified object
    """
    plocals = sys._getframe(1).f_locals
    if plocals.has_key(v):
        return plocals[v]
    if globals().has_key(v):
        return globals()[v]
    if __builtins__.locals().has_key(v):        
        return __builtins__.locals()[v]
    return obj

    
def test():
    """
    Test isa() and ifno() functions:
    """
    
    # Totally useless routine. ;)
    import random
    for n in range(25):
        
        # Delete a random x,y,z coordinate to
        # simulate an unrealiabe data source. 
        d = random.choice([1,2,3])
        if d==1:
            if isa('x'): del x
        elif d==2:
            if isa('y'): del y
        else:
            if isa('z'): del z

        # Replace the missing Varible with a random number.
        r = int(random.random()*100)
        x, y, z = ifno('x',r), ifno('y',r), ifno('z',r)    
        print x, y, z


if __name__ == '__main__':
    test()
    
#-------------------------------------




More information about the Python-list mailing list