self vs. @ (Python and Ruby)

March 2, 2006

Until a few days ago, I considered myself a “faithful” Pythonist. I liked ObjectiveC. I liked a bunch of other languages (notably Prolog or Haskell). I quite liked C++ too. But in fact my true love was Python.

I know it is strange to talk about “love”. That is of course unproper. Unfortunately I’ve no time to find a better word to express the thing. Let say that I liked to code in Python independently of what I was coding. Quite the same thing than I love using MacOS independently of the task, while I may be forced to use Windows because of the task, but would not use it if it was up to me (few… complicated period).

Today I read this (pointles) discussion about “self” in Python. There are people who

  • Does not like to self.foo
  • Does not like to
    def foo(self, else):
      # code
    

I perfectly understand this position. In fact I do not really like having to reference self explicitly everytime (even if I fully understand why python does this). Of course it makes sense.

I’m calling methods /accessing variables of an object. So I should use the conventional way object.method|variable. There should be only one way to do it. For example Java “optional” this sucks. At least in my opinion. It has no purpose in method/variable stuff. Some use it to make clear that they’re referencing instance variables, some use a m_var notation.
If you are a C++ programmer you could be using var_ or (if you haven’t read the standard quite recently) _var

Of course having a clear and readable way to distinguish instance variables methods is good. That is clear. It makes you easier to read.

self is boring. I often forgot it and got error messages (about the ninth consecutive programming hour this is not the worst thing I do, however). In this sense I also forget the ruby @. And it’s better a spectacular error than a hidden bug. So… go on

I quite don’t like having specify self among the formal parameters. You schiznick, don’t you know its a method? Actualy Python does not. If you take a normal function and bind it to an object, the first formal parameter is the object itself. So its better that function was meant from the beginning that way and had a starting self parameter.

Of course this is boring, but its necessary and has not real disadvantages (a part from some additional typing.. something that with a decent editor is not a concern Aquamacs/Emacs or TextMate strongly advised).

And so all the knots get back to the comb. Python has this boring self everywhere. And it is there and should be there. Ruby hasn’t.
The @ makes the code quite readable (expecially with a decent editor). Of course it prevents name clashes and such. Having not to pass self to functions also makes it easier to refactor from functions to methods (ok, we know, in ruby every function is a method, but that’s not the point). This in the case that the method uses no instance variables.

But…

But Ruby treats variables and methods differently. Instance variables need a “special” syntax. Methods don’t. It’s not clear if a method is a function or not (of course it does the Right Thing)

    irb(main):001:0] def foo; "foo"; end
    =] nil
    irb(main):002:0] class Bar; def foo; "dont foo" ; end
    irb(main):003:1] def bar; foo; end
    irb(main):004:1] end
    =] nil
    irb(main):005:0] b = Bar.new
    =] #
    irb(main):006:0] puts b.bar
    dont foo
    =] nil

As I said it does the Right Thing… I’m just talking about readability. Of course you can use self in ruby too… but well. This is something I would have preferred solved in another way, even if right at the moment I’m find quite acceptable to renounce to have “one way” for a bit more pragmatism.

Advertisements

Some more things I love about Ruby

February 26, 2006

First of all, I love %w{ }. It is wonderful. When prototyping it makes me save lot of digits. I know it’s a bit perlish (exspecially because you can also %w[ ] or %w/ /), but it is a great feature.

The %x{ } for commands (and ``). Yeah, perlish. But I needed it in some system automation scripts in Python. I know I could use subprocess… but sometimes I need something more stupid. I wrote a class for this (and you can find it in my blog).

Regexps… I’m a python fan… but I have to admit perl’s syntax makes a lot of sense (and it is the one I have in sed or vim too, at least to some degree). Quite like that syntax in a cleaner environment.

Having the % operator on strings is good. It resembles me Python. I suppose it’s a bit less powerful (I think it works only with lists, but since you can use #{} in ruby strings, the need for dictionaries is small). Moreover some of the most un-pythonic code I wrote is due to “creating” dictionaries. If you don’t take care, you may find yourself with troubles. Of course even the #{} can be abused and so be source of problems.

<< on strings and arrays. I quite liked streams in C++. Yeah, not the same thing, but…

I’ll write more later… (there are also things I don’t like, but I should study more to fully understand them).


Ruby arrays and matrices

February 22, 2006

One of the first things you learn when reading a book on Ruby is that “variables” hold references to objects. Consider


a = Foo.new
b = a

Both a and b contain the same instance of the object. Fine. Simple. Java does the same and so does Python. You just know what that means and you know that if you want a copy instead (that is to say b and a should change indipendently) you must dup or clone them.


a = Foo.new
b = a.dup

Now it comes to arrays. Ruby arrays are much like Python list. They are powerful objects. And have something Python lists do not have, some more constructor. From the ruby doc:

Array::new
Array.new(size=0, obj=nil)
Array.new(array)
Array.new(size) {|index| block }

Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is calculated by passing the element’s index to the given block and storing the return value.

We analyze the very first constructor. It makes perfectly sense: consider this:

  l = Array.new(5, "") # ["", "", "", "", ""]
  l[1] ="foo"
  l # ["", "foo", "", "", ""]

Now consider this:

    l = Array.new(5, []) # [[], [], [], [], []]
    els = %w{ el1 el2 el3 el4 el5 }
    l.each_index { | index | l[index].push els[index] }
    #  [
    #    ["el1", "el2", "el3", "el4", "el5"], 
    #    ["el1", "el2", "el3", "el4", "el5"], 
    #    ["el1", "el2", "el3", "el4", "el5"], 
    #    ["el1", "el2", "el3", "el4", "el5"], 
    #    ["el1", "el2", "el3", "el4", "el5"]
    #  ]

This is the correct result. But this probably is not what we wanted to obtain. The “correct way to initialize l” would have been

    l = Array.new(5) { | dummy | Array.new } # [[], [], [], [], []]
    els = %w{ el1 el2 el3 el4 el5 }
    l.each_index {| index | l[index].push els[index] }
    # [["el1"], ["el2"], ["el3"], ["el4"], ["el5"]]

This time for each line we are creating a “new” empty list, not the very same one.

In this case you probably should have been using the Matrix class, anyway.


Ruby vs. Python? [no, Ruby vs. Ruby ]

February 20, 2006

In fact this is not a Ruby vs. Python list. I know not enought Ruby and I love Python to much :). It’s more a picture of the first impressions I had on Ruby after I seriously began studying it.

This is a quick list of thoughts. I’m probably adding more stuff later. In fact I’m reaaly amazed. Ruby is really hackish, but it’s also neat and clean. It may sound strange… but I’m afraid I’m gonna love ruby more than Python: it addresses many of the things I come to dislike in Python.

Some stuff I like

  • Adding dynamically stuff to classes. The syntax is clean and obvious
    class MyClass
      def aMethod
        puts "Called aMethod"
      end
    end
    
    m = MyClass.new
    
    begin
      m.aMethod2
    rescue NoMethodError => ex
      puts "Failed to call #{ex}"
    end
    
    class MyClass
      def aMethod2
          puts "Called aMethod2"
      end
    end
    
    m.aMethod2

    In Python for example it is not that clean. The ruby code looks more like ObjectiveC categories (even if in fact you don’t specify a category, of course, since ruby does not need categories).

  • private, protected, public modifiers. Being dynamic they do not limit me in any way (if I need I can dynamically change this)
    class MyClass
      protected
      def aMethod
        puts "Called aMethod"
      end
    end
    
    m = MyClass.new
    
    begin
      m.aMethod
    rescue NoMethodError => ex
      puts "Failed to call #{ex}"
    end
    
    class MyClass
      public :aMethod
    end
    
    m.aMethod

    Moreover I can’t think to a cleaner syntax to do this. Of course one can argue that they aren’t really necessary. Of course, but if you want they do give you a little bit of control, but they don’t limit you in any way.

  • Object#freeze: if you suspect that some unknown portion of code is setting a variable to a bogus value, try freezing the variable. The culprit will then be caught during the attempt to modify the variable.
  • I love postfixed control clauses. In fact if used with moderation they can augment code readbility (and of course if abused they make it less readable). However, it is pretty logigal to say do_something if something_else. In fact since ruby has blocks it is ok also to write
    begin
        # some stuff
    end if condition
    

    maybe not everyone agrees

  • Accessors are great. Using attr and similar constructs is great. I also find quite more readable to “assign” with foo= than using more Javesque setFoo(val). In fact properties in Python work in a similar fashion, even if maybe a bit more verbose (however, I think they make it clearer how to document code, but this is a ruby aspect I’ve not yet exploited)
  • Gems: I think python needs something like that. Pimp is not that good, in my opinion, of course.

Stuff I don’t know if I like or not

  • Not having to write parentheses with no-argument methods. I’ve not yet discovered if I like it or not.
  • All the $_… They are used a lot in Perl. I like it, but I’m afraid it can mess things up.

Stuff I dislike

  • I don’t like passing strings to require. In fact it can have advantages, but I prefer the pythonic import foo to require "foo".
  • The try catch semantic of try/catch, makes me think to some kind of disguised goto. I’m sure I’m wrong… but
  • I’d like to have something like Perl use strict;. It’s something I miss in Python (even if with pychecker you can just live without it). Now I’ve got to find some kind of “use strict” or “rubycheck”.
  • Assignment is an expression. This directly leads to code like
    a = true
    b = false
    print b if b=a
    

    and we imagine the programmer wanted to write

    a = true
    b = false
    print b if b==a
    

    However in Ruby almost everything is an expression, and it has quite a lot of advantages. So we have to tolerate the “=” for “==” problem.


Ruby 0.0

February 17, 2006

Today I decided to take some time and have a look at Ruby. I found online a version of Programming Ruby and started reading it. In fact I knew I was going to like Ruby. In fact the first time I took contact with it I quite liked it, even if I didn’t fully exploit its capabilities.

Well… let’s see how it goes. Right at the moment the first thing I wrote is

class Employee
  attr_reader :wage, :name
  attr_writer :wage
  
  def initialize(name, surname, wage)
    @name = name
    @surname = surname
    @wage = wage
  end
  
  def surname
    @surname
  end
  
  def to_s  
    "#{name} #{surname} (#{wage})"
  end
  protected :wage=
  
end

class Manager > Employee
  def initialize(name, surname, wage, employees=[])
    super(name, surname, wage)
    @employees = employees
  end
  
  def setWage(emp, wage)
    emp.wage = wage
    emp
  end
   
  def to_s
    super + @employees.collect{|e| "\n  #{e}"}.join("")
  end
end

mr = Employee.new("Jack", "Bravo", "1000€")
mc = Employee.new("Michael", "Charlie", "300€")
mngr = Manager.new("Angus", "Smith", "10000€", [mr, mc])
mngr.setWage(mc, "700€")
puts mngr