Symbols as parameters?
andreengels at gmail.com
Thu Jan 21 09:18:32 CET 2010
On Thu, Jan 21, 2010 at 8:43 AM, Martin Drautzburg
<Martin.Drautzburg 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
> 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.
> 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
> So it should look something like this
> ... magic, magic ...
> ... 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?
It probably can be done, but in my opinion even it can, it would be
ugly. I would just define "up" as some global constant - I don't see
why it would be a problem that it's defined when you don't need it. In
fact, I think it would be beneficial - you can then have
direction-valued variables, so that you can (for example) implement
"go the same direction I went last time". If that kind of thing
happens more often, it might be useful to have a Direction class, to
be able to easily program in things like "the opposite of up is down"
and "right from right is back".
André Engels, andreengels at gmail.com
More information about the Python-list