Symbols as parameters?

Javier Collado javier.collado at gmail.com
Thu Jan 21 09:38:24 CET 2010


Hello,

I'd say that isn't totally incorrect to use strings instead of
symbols. Please note that in other programming languages symbols,
atoms and the like are in fact immutable strings, which is what python
provides by default.

Best regards,
    Javier

2010/1/21 Alf P. Steinbach <alfps at start.no>:
> * Martin Drautzburg:
>>
>> 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 ...
>> 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?
>
>>>> def move( direction ):
> ...   print( "move " + str( direction ) )
> ...
>>>> move( "up" )
> move up
>>>>
>>>> class using_directions:
> ...     up = 42
> ...     move( up )
> ...
> move 42
>>>> up
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> NameError: name 'up' is not defined
>>>> _
>
>
> Of course it's an abuse of the language. :-)
>
> So I wouldn't recommend it, but it's perhaps worth having seen it.
>
>
> Cheers & hth.,
>
> - Alf
>
> PS: I hope this was not a homework question.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list