Symbols as parameters?

Martin Drautzburg Martin.Drautzburg at web.de
Thu Jan 21 16:51:34 EST 2010


Thanks for all the answers. Let me summarize

(1) I fail to see the relevance of 
 >>> def move( direction ):
...   print( "move " + str( direction ) )
...
 >>> move( "up" )
move up

not only in the context of my question. And I don't see an abuse of the
language either. Maybe this could pass as a Zen Puzzle.

(2) Using enum's was suggested. That is good to know, but again it is
just a way to define constants in the caller's namespace.

(3) Then somone suggested to tie the constants to the function itself,
as in
def move(direction):
    print "moving %s" % direction

move.UP = 'up'
move.DOWN = 'down'

This is quite nice. Then again the "move." is just some object which
allows attributes, and which only happens to have the same name as the
function. Well in this case it IS the function, alright, but I could
just as well have used a Class as in

class m: pass
m.UP = 'up'


(4) Finally someone mentioned DSLs. I guess thats absolutely correct.
This is what I am struggeling to achieve. I did a little googling ("how
to write DSLs in python"), but haven't found anything appealing yet.
Any pointers would be appreciated.

(5) Here is something I came up with myself:

def symbols(aDict):
    aDict["foo"] = "bar"

def someFunction(aFoo):
    print aFoo

symbols(locals())
someFunction (foo) #Eh voila: foo is magically defined

prints: bar

The call to symbols(locals()) is the "magic, magic" I supected would be
required in my original posting. If someFunction was a member of a
class, the symbols would be properly tied to that class (albeit not the
individual function), but still good enough. I suppose I could wrap it
in a decorator, which would also do the "unmagic". 

In any case, getting the context right seems to be the biggest problem.
If I don't want to pollute my namespace, those symbols need to be
defined in some context but undefined in others. AFAIK there are not
really "blocks" in python and lexical scoping is present primarily in
functions. 







More information about the Python-list mailing list