ruby rocks, python not

Posted by Simon on March 18, 2008 at 09:54 PM

So I'm just doing some python programming, just a few hours, and already I'm missin' ruby.

python dictionary, is a certain key set?
if self.params['foo']:

oh no, that's won't work. Hmm... How about
if defined(self.params['foo'])

Nope... no such luck, there's NO WAY to find out if a variable is defined in python. Finally after futzking around online I find out that the ONLY way to do it reliably in any situation is to—get this—catch an exception. Except since I'm dealing with a dictionary I can use this (undocumented) method:
if self.params.has_key('foo'):

That's so lame. In ruby, you can do any of these:
if @params['foo']
if @params['foo'].nil?
if defined? @params['foo']

Speaking of which, now that I get it, the @foo syntax for an instance variable (stupidly called a "data attribute" in python) is great. So much more obvious & compact than self.foo.

Python also forces you to do some things that I have happily adapted to giving up in ruby. Like calling functions without brackets, isn't
defined? @params
so much prettier than
defined?(@params)

Yes it is. And also, I've started naming my functions with ?s if they yield a boolean and ! if they make a change in place or generally perform a destructive edit—nice.

And ruby's blocks—I love you!

      download = Download.new do |d|

d.user = @user
d.name = my_name
end


And unless and the if/unless modifiers... I could go on forever. Why don't you read the insane book?

Hierarchy: previous, next

Comments

There are 19 comments on this post. Post yours →

"Nope... no such luck, there's NO WAY to find out if a variable is defined in python."

It's actually easy in Python:

>>> self = {'foo': 'bar', 'baz': 'bap'}
>>> self.has_key('foo')
True
>>> self.has_key('blarg')
False

For individual variables, rather than dictionary keys, you can test using the same has_key() method, but for the locals() dictionary:

>>> foo = 'bar'
>>> locals().has_key('foo')
True
>>> locals().has_key('baz')
False

Easy, peasy.

Alastair Tse

It's actually just:

params = {
'foo': 1,
}

if 'foo' in params:
print 'self.params['foo'] ok'

if 'bar' in params:
print 'self.params['bar'] ok'

Testarossa

Related:

http://coffeeghost.net/2008/03/19/your-ignorance-does-not-make-a-programming-language-suck/

Simon

@Ryan: that method is not only ugly, but also unreliable: see http://mail.python.org/pipermail/python-list/2002-July/156865.html (since the variable is from an outside scope, it's neither local or global......)

@Alastair: that is certainly better, but not as good as simply testing it directly as in ruby. It should Just Work.

@ Testarossa: Fortunately, python doesn't actually SUCK. Then I wouldn't use it (Perl does suck, so I don't use it). But ruby is better.

Simon,

The problem you cited in your post was testing whether a dictionary contains a key. I mentioned one way, and Alastair mentioned a better one:

>>> params = {'foo': 1}
>>> key1 = 'foo'
>>> key2 = 'bar'
>>> key1 in params
True
>>> key2 in params
False

As far as I can see, this syntax *is* just testing it directly. :)

As for the more general problem of discovering whether a variable has been initialized, thanks for pointing out the problem with the method I gave. It does appear that a try / except block is the only way to be certain.

However, as one Pythonista put it:

"Personally, I find it quite nice
that an ugly architecture (such as one based on whether a variable
is already defined/initialized rather than initializing it at the
start with a unique value and testing for that!) requires an ugly
way of expressing it."

http://www.thescripts.com/forum/thread20887.html

Cheers!

I made a text selection in my web browser, right clicked and Googled for "python dictionary, is a certain key set". Even the number one ("I'm feeling lucky!") link that comes up answers your question.

Tired: Ignorance. Wired: Learning.

Sim

>>> params = {'foo': 1}
>>> key1 = 'foo'
>>> key2 = 'bar'
>>> try: print 'key1:', params[key1]
... except KeyError: print 'not set'
...
key1: 1
>>> try: print 'key2:', params[key2]
... except KeyError: print 'not set'
...
key2: not set


Yet another way to do it that is usually my favorite since I believe it is actually faster.

-Sim

markus

Checking for exceptions is a bad way to do it. Python is such a nice language, why doesn't it have support for something like this?

Haha. I was going to post here and say "I feel your pain, Simon" as I regularly bash my head against the wall at the stupidity of PHP when compared to Perl....

... and then I read that you are NOT among the initiated! :) What could you possibly have against Perl???!!!

candu

If you don't like Python's default dict, roll your own...

class MyDict(dict):
def __getitem__(self, key):
if key in self:
return dict.__getitem__(self, key)
return None

d = MyDict()
d[42] = 1729
s = d[42] or "not found..."; print s
s = d[666] or "not found..."; print s

Of course, you run into problems if None is a valid value in your dict - but the real point is that it's dead easy to _make_ Python do what you want!

Maybe Ruby is easier to use here but the numbers still say that Python is more popular :-)

mykhal

self.params.get('foo')

I've always felt that the ability to do these two is a sign of a fundamentally-flawed language.

if @params['foo']
if defined? @params['foo']

I'd only use Ruby if you paid me (and paid me well at that) because of Perl-inspired features like implicit returns and, if I'm reading those two lines right, implicit variable definition.

My advice is to open up Python's interactive interpreter and type "import this" to pull up the easter egg copy of "The Zen of Python".

The behaviour you applaud and I condemn runs up against the following excerpted lines:

Explicit is better than implicit.
Special cases aren't special enough to break the rules.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one— and preferably only one —obvious way to do it.

I loved my CHI! But when it broke four months after I had paid for it, I found out some bad news. The one year warranty is VOID if you buy it from Amazon, because they are not an authorized dealer!

Some models, like the Original CHI, have a fixed temperature. This can be an issue if you have fine or delicate hair. If that describes your hair, than you should look to using a newer model like the CHI Turbo or Nano which come with a variable temperature.

Best quality and services of the finest Christian Louboutin Shoes are sold at usachristianlouboutin.com, but we don't stop just there. Our aim is to provide you with first class services and make your online shopping experience a wonderful one.

vibram five fingers
five fingers
vibram shoes
vibram five fingers shoes
five fingers shoes
vibram five fingers shoe
cheap vibram five fingers shoes
vibram five fingers shoes discount
vibram five fingers shoes on sale
vibram five fingers shoes for sale
buy vibram five fingers shoes
authetic vibram five fingers shoes
vibram five fingers shoes clearance
new vibram five fingers shoes
vibram five fingers shoes new arrival
vibram five fingers 2010
vibram five fingers UK
vibram five fingers US
top quality vibram five fingers
best vibram five fingers
lowest price vibram five fingers
cheap christian louboutin shoes
yves saint laurent shoes sale
new fendi shoes
buy jimmy choo shoe
manolo blahnik shoes discount
cheap yves saint Laurent shoes
cheap fendi shoes
cheap fimmy choo
cheap manolo blahnik shoes
christian louboutin shoes sale
fendi shoes sale
jimmy choo shoes sale
manolo blahnik shoes sale
new christian louboutin shoes
new yves saint laurent shoes
new jimmy choo shoes
new manolo blahnik shoes
buy christian louboutin shoes
buy yves saint Laurent shoes
buy fendi shoes
buy manolo blahnik shoes
mbt shoes
mbt sneakers
mbt walking shoes
mbt footwear
mbt shoe
mbts
cheap mbt shoes
mbt shoes sale
mbt shoes on sale
mbt shoes for sale
mbt shoes discount
authentic mbt shoes
mbt shoes clearance
buy mbt shoes
best mbt shoes online
mbt shoes UK
mbt shoes US
cheapest mbt shoes
latest mbt shoes
top quality mbt shoes
new mbt shoes

sdfsd

sdfsdfsdf

dfsdfsdf

sdffffffffffffff

Post a comment

Required fields in bold.