Proposal for adding symbols within Python

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Nov 15 05:53:23 EST 2005


On Tue, 15 Nov 2005 01:57:53 -0800, Ben Sizer wrote:

>> I don't think I even understand what the objection is.  What is
>> needed is a code fragment that shows how the use of strings is
>> untenable.
> 
> myObject.value = 'value1'
> 
> #... 100 lines of code elided...
> 
> if myObject.value = 'Value1':
>     do_right_thing()
> else:
>     do_wrong_thing()
> 
> 
> I don't actually think string use is 'untenable', but it is definitely
> more error-prone. With some sort of named object on the right hand side
> you will at least get a helpful NameError.

It is moments like this that I'm not too proud to admit I learnt some good
techniques from Pascal:

# define some pseudo-constants
RIGHT_THING = 'value1'
WRONG_THING = 'some other value'
INCHES_TO_FEET = 12
CM_TO_METRES = 100

# ...

myObject.value = RIGHT_THING
 
#... 100 lines of code elided...

if myObject.value = RIGHT_THING:
    do_right_thing()
else:
    do_wrong_thing()


It isn't always appropriate or necessary to define "constants" (and I
sometimes wish that Python would enforce assign-once names), but they can
help avoid some silly mistakes.



-- 
Steven.




More information about the Python-list mailing list