Difference in Python and Ruby interactive shells

Steve Juranich sjuranic at gmail.com
Tue Apr 4 10:43:09 EDT 2006


dmh2000 wrote:

> I am experimenting with the interactive interpreter environments of
> Python and Ruby and I ran into what seems to be a fundamental
> difference. However I may be doing something wrong in Python. Please
> comment and correct me if I am wrong
> 
> In both languages, you can start up the interactive interpreter
> ('python' and 'irb'), load source files and do stuff, like create
> objects and call their methods. When you want to change something, you
> can edit those same source files outside the environment and reload
> them from within the interactive environment. But, here is the
> difference: with Python, when you reload the source file (module in
> Python terms), it seems that your existing variables stay bound to the
> implementations from the old version of the module. In Ruby, after a
> reload, your existing variables point to the new implementation. At
> least, that is what happens with classes and their methods.  This means
> that in Python, if you have an application built up interactively, with
> references to objects, data structures pointing to objects, etc., you
> would have to reconstruct that application to get the new
> implementation. With Ruby, when you load the new implementation, you
> get it immediately.

This is correct.  I'm a bit fuzzy on the details, so some of this might be
wrong, but here's what's going on (I'm pretty sure):

When Python loads (or reloads) a module, it encounters a `class' block,
which causes it to create a new type in memory.  The instances created from
this type are bound to the type object.  This means that after a reload,
your "B" class is pointing to a different object in memory.  However, all
of your previous instances are still bound to the old definition (which is
still in memory, it's just not bound to the "B" name any more).  As a
simple test, do 'x.__class__ is y.__class__'.  This should return False.

Ruby, on the other hand, allows you to redefine classes on the fly.  So when
Ruby reads a 'class' block, it's either (1) redefining a previously defined
object's definition, or (2) creating a new class with the definition in the
block.

I *think* that the reason for this is that the Python virtual machine (aka,
the interpreter) is much more efficient than the Ruby VM.  So if you want
fast code, I'd stick with Python.  However, if you regularly build large
applications in memory from an interactive interpreter, then perhaps Ruby
is the way for you to go. :-)

Cheers.
-- 
Steve Juranich
Tucson, AZ
USA




More information about the Python-list mailing list