by simon baird

Tuesday, May 13, 2008

python otherwise

Well other than the venting in my last post on python, it's actually not been too bad. Random thoughts from a part-time ruby programmer learning python:
  • the self thing in class methods is a little funky but it's not bothering me at all.
  • the ternary expressions I've started to really like. ie: x = 'foo' if some_condition else 'bar' beats x = some_condition ? 'foo' : 'bar' hands down for readability
  • the significant indenting thing is okay. It took a little adjustment, but yeah whatever. a shift width of two isn't enough for me though. four is fine.
  • stuff like str(some_object), len(some_object), int(some_object) versus some_object.to_s, some_object.length, some_object.to_i, I can stomach, but it feels like a backwards step
  • it took me ages to figure out how to display local time. it seems over-complicated.
  • seems less helpful that (but it could just be I'm more accustomed to it)
  • Can python do stuff like this? Maybe it can. (I'm a noob, bigtime).
class String
  def my_thing
    // do something cool

"Hello there".my_thing

I just read that and it sounds a little like I'm bitching. What I'm trying to say here is that python is alright. But also, that I like ruby a lot. Did that come across..?


otherchirps said...

well, could always use some_object.__str__(), or some_object.__len__() if you like that way instead. :)

For the local time, there's the datetime module. There's a new PEP, 3108, for reorganising the standard libs, culling the cruft. But they don't mention the time/datetime modules... kind of wish those were included. Be nice to have one way, and preferably only one way, to get to that stuff.

About the modification of existing classes, turns out you can most of the time. But for "builtin" types, like string, int, etc... those are locked down. You can subclass them, but not fiddle directly.

From what I can gather, seems that folks are worried about people pulling the rug out of you, by doing silly things like making an integer addition map to multiply instead. Seems a bit pointless to lock them up to me, since any other class you make is fair game to modify like this anyway.

>>> class MyClass(object):
>>> ...def foo(self):
>>> ......print "foo"
>>> ...
>>> m = MyClass()
>>> def bar(self):
>>> ...print "bar"
>>> ...
>>> = bar

Also, when folks accuse python of being bug-prone, since you can't hide class members (ie. no private parts... there's _ and __ prefixes, but that's just for show. The members are still available), the usual response I see, and like, is that python generally trusts the programmer to not be an idiot. :) Seems that this trust doesn't apply to the builtin types.

simon said...

What, like this kind of thing..? :)

irb(main):001:0> class Fixnum
irb(main):002:1> ..def +(x)
irb(main):003:2> ....5
irb(main):004:2> ..end
irb(main):005:1> end
=> nil
irb(main):006:0> 2 + 2
=> 5

(maniacal laughter...)