Symbols as parameters?

Carl Banks pavlovevidence at gmail.com
Thu Jan 21 05:25:36 EST 2010


On Jan 20, 11:43 pm, Martin Drautzburg <Martin.Drautzb... at web.de>
wrote:
> Hello all,
>
> When passing parameters to a function, you sometimes need a paramter
> which can only assume certain values, e.g.
>
>         def move (direction):
>                 ...
> If direction can only be "up", "down", "left" or "right", you can solve
> this by passing strings, but this is not quite to the point:
>
>         - you could pass invalid strings easily
>         - you need to quote thigs, which is a nuisance
>         - the parameter IS REALLY NOT A STRING, but a direction

Nothing you can pass to the function is really a direction.  A symbol
is no more a direction than a string is.


> Alternatively you could export such symbols, so when you "import *" you
> have them available in the caller's namespace. But that forces you
> to "import *" which pollutes your namespace.

No it doesn't.  You can still write module.UP in the function call, or
you can write from module import UP.


> What I am really looking for is a way
>
>         - to be able to call move(up)
>         - having the "up" symbol only in the context of the function call

Short answer is, you can't do it.

Long answer is, you don't really want to have a symbol that's only in
context during the function call, because you might just want to write
some code that operates on directions (e.g., return random.choice
([UP,DOWN]), but it's a moot point since you can't do it.

> So it should look something like this
>
> ... magic, magic ...
> move(up)
> ... unmagic, unmagic ...
> print up
>
> This should complain that "up" is not defined during the "print" call,
> but not when move() is called. And of course there should be as little
> magic as possible.
>
> Any way to achieve this?

Apart from writing a custom DSL (domain specific language), no.

It is not, in case your were wondering, a feature that would be easily
added to Python (the moratorium on new syntax notwithstanding).
Python wouldn't be able to do this at compile time (since Python
doesn't know what symbols refer to till run time).  I convinced myself
that it would be techincally possible to do it at run time, but at a
penalty of higher function call overhead (which is already high enough
as it is).  And with the performance hit, extra scoping complexity,
the inability to be used outside the function context, and no real
benefit except to save typing, I don't see it ever being approved.


Carl Banks



More information about the Python-list mailing list