cd $HOME

Read-Only variables

I was puzzled tonight concerning Ruby and its behavior regarding Standard Objects. For instance, redefining True is perfectly legal in Python:

>>> def is_True_true():
...   if True:
...     print "True is true" 
...   else:
...     print "True is false" 
...-
>>> is_True_true()
True is true
>>> True=False
>>> is_True_true()
True is false
Boolean values are in Python two constant objects. You can redefine them, but their scope becomes local:

>>> is_True_true()
True is true
>>> def evil():
...   True=False
...-
>>> evil()
>>> is_True_true()
True is true
This behavior may be a little confusing sometimes:

>>> type(True)
<type 'bool'>
>>> True=12
>>> type(True)
<type 'int'>
>>> False=12
>>> False == True
True

Like in Ruby, booleans are implemented in Python using the Signleton pattern:

The values False and True will be singletons, like None. Because the type has two values, perhaps these should be called “doubletons”?

See PEP 285

In Ruby however, these objects cannot be changed. true for instance is (the single) instance of class TrueClass, and an exception is raised whenever one tries to modify them. It is also the case for false, nil, etc.

Hence a question: why some attributes are locked in Ruby? Dave Thomas in Programming Ruby argues:

After all, you probably don’t want to change the meaning of true halfway through your program (except perhaps if you’re a politician).

And what if I was a politician? Since every class is open in Ruby, doesn’t that mean that it allows the programmer to do whatever he wants? Is it more dangerous for true to be modifiable compared to +?

irb(main):001:0> class Fixnum
irb(main):002:1>   def +(arg)
irb(main):003:2>    return self-arg
irb(main):004:2>   end
irb(main):005:1> end
=> nil
irb(main):006:0> 1+1
=> 0

Ruby doesn’t try to prevent the coder to write stupid code, as C or C++ does by using types for instance. So why a selected set of special objects doesn’t follow this philosophy?

Back

Comments

Phil (http://philadams.net) on March 02, 2008 20:36 (170 days ago) wrote

we should not be so geeky that this is what we talk about over pizza and beer… ;)



The content of this field is kept private and will not be shown publicly.