How does Moose compare to Python's OO system? [closed]
Asked Answered
I

2

17

My original question was too vague and was "closed as not constructive." As such, I will revise the question so that it caters to the answers that have already been posted. :-)

I am interested in the differences between Perl's Moose OO framework Moose and Python's stock OO framework. As a first point of comparison, how easy is it to create a simple class with a couple of attributes and a handful of methods?

Now, if this question gets reopened, I would also like to know: How easy is it to refactor code in the future if I decide to make an attribute "read only"? In other words, what steps would I have to take to change an attribute from being readable and writable to being read only? (I know, it's bad to change an API, but let's assume I'm working on something internally and realize in the middle of my implementation that an attribute really should be read-only.)

Ilysa answered 8/2, 2012 at 1:49 Comment(4)
This is hilarious considering that Perl took much of its original object system from Python. Calling Python's great is a very curious view.Caloyer
This comment doesn't make any sense in light of my latest edit. Originally, I said that I had heard that Python's OO is great. What I meant by that is "Python provides syntactic sugar so that creating a class is really easy."Ilysa
@David Mertens: Regarding your edit - To change an attribute from read/write to read only is easy. For eg. change has someattr => (is=>'rw'); to has someattr => (is=>'ro'); After this change all attempts to write to attribute will give a run-time error, for eg. $x->someattr("foo"); (setter) would throw an error whereas the $x->someattr (getter) is fine.Wilton
Well, the comment did make perfect sense (to me) when I made it :)Caloyer
S
11

From having used both, Moose's big strength is it's brevity. Compare classic perl OO:

package Person;
use strict;
use warnings;

sub new {
  my $self = {};
  my $class = ref($proto) || $proto;
  $self->{FIRST_NAME} = undef;
  $self->{LAST_NAME} = undef;
  bless ($self, $class);
  return $self;
}

sub first_name {
  my $self = shift;
  if (@_) { $self->{FIRST_NAME} = shift }
  return $self->{FIRST_NAME};
}

sub last_name {
  my $self = shift;
  if (@_) { $self->{LAST_NAME} = shift }
  return $self->{LAST_NAME};
}

1;

with Moose:

package Person;
use Moose;
use namespace::autoclean;

has 'first_name' => (is  => 'rw', isa => 'Str',);
has 'last_name' => (is  => 'rw', isa => 'Str',);

__PACKAGE__->meta->make_immutable;
1;

And I'm pretty much sold, but Moose is just getting start. I think my next favorite feature was the Types, which could really simplify a program over a large codebase and stop a whole range of nasty bugs. For instance, it would have nicely handled one I got bitten by the other day (while coding Python, actually) where a certain property of an object was a Date in some instances, but a string representing a date in others.

Haven't heard of any alternative OO system for python.

Scyphate answered 8/2, 2012 at 2:55 Comment(12)
It seems to me that an alternative OO system for python would be unnecessary as OO was a fundamental quality of the language from the start, while OO for Perl was more of an afterthought. Thus Perl requires wrappers and extensions to bring about OODortheydorthy
@Dortheydorthy nonsense, especially given that Perl's and Python's basic OO models are the same, and Python's property for instance was an afterthought added late in the game, Python used to have DFS MRO and later retrofitted C3, etc.Kindless
@Dortheydorthy - I actually wrote something like that at first, but I erased it because comparing the two, IMO, Moose is pretty far ahead of stock python OO in things like having typed properties and enums (but that might just be my bias towards static typing.)Scyphate
@Dortheydorthy - "OO for Perl was more of an afterthought." You have repeated what many have said in ignorance. If you have nothing intelligent to say about Perl's OO then I would appreciate if you would stay on the sidelines.Ilysa
@ToddGardner, thank you for your response. This is certainly a good reason to use Moose over classic Perl OOP. However, the thrust of my question was really about Moose vs Python. Are similar constructions possible with Python? Does Python have something akin to Types?Ilysa
David, if my text was repeated it was due to user input error and not ignorance. No need to be rude. I also did not suggest Moose or perl were inferior. I simply auggested that an alternate OO system for python seems unnessesary.Dortheydorthy
Yes David I agree you can write perl OO without extensions or wrappers and yes I have little experience with perl. My comment was based on the general consensus I have interpreted that it had been a mess until moose. And yet again, my only real statement here was regarding python not needing alternate OO solutions. Lets not nitpick and start a perl python flame warDortheydorthy
@jdi, I'm sorry. The thrust of my interest is a comparison between Moose and Python, not a discussion of alternative Python object models. I'll revise my post and remove the last question as it is tangential.Ilysa
@DavidMertens You owe jdi an apology. OO for Perl was an afterthought, albeit one that came so long ago that it doesn't seem like it anymore. I used Perl before objects were added to it (they came along in Perl 5). Don't be so defensive. While he might have misspoken about Perl requiring wrappers to do OO, it isn't much of an exaggeration: "native" Perl just doesn't emphasize that style of programming heavily. I'm not anti-Perl in any way - I chose to do a college senior paper on it - but I doubt even Larry would strongly disagree with jdi's point.Hamamatsu
@KirkStrauser, I have revised my question and have removed my less appropriate response. What you say here about Perl is exactly right and I wish jdi had been more precise with his statements. Thanks for clarifying for anybody else who might read.Ilysa
@DavidMertens I also noticed that you replied to him about 8 seconds before I replied to you. :-D Anyway, I also tried to give you an example of Python to compare to the Perl snippets so you can judge for yourself.Hamamatsu
Please use chat for extended discussions. I'm not wiping this thread because it is somewhat related, but comments here are really starting to approach more noise than signal.Stringency
H
3

Python's OO strength is probably in its pervasiveness. That is, the built-in OO system is so simple and the syntax is so approachable that it's far and away the dominant Python programming paradigm. For instance, the rough equivalent of Todd Gardner's first "Person" example might work like:

class Person:
    def __init__(self):
        self.firstname = None
        self.lastname = None

me = Person()
me.firstname = 'Kirk'  # These two lines update instance attributes
me.lastname = 'Strauser'

This version defines getters and setters for accessing the values:

class AnotherPerson:
    def __init__(self):
        self._firstname = None
        self._lastname = None

    @property
    def firstname(self):
        return self._firstname

    @firstname.setter
    def firstname(self, newname):
        self._firstname = newname

    @property
    def lastname(self):
        return self._lastname

    @lastname.setter
    def lastname(self, newname):
        self._lastname = newname

you = AnotherPerson()
you.firstname = 'David'  # These two lines call instance methods
you.lastname = 'Mertens'

Python and Perl are roughly equivalent in power, flexibility, and expressiveness. If you can do something in one, you can probably do it similarly in the other. However, I think Python has the clear advantage in simple OO design - to the point that there's not been a reason for any alternative object models to gain significant traction.

Hamamatsu answered 8/2, 2012 at 4:28 Comment(5)
thanks. Combined with Tood Gardner's response, we have a simple side-by-side comparison and Moose and Python OO look about the same.Ilysa
In Moose, you get basic getters and setters for free: my $me=Person->new;$me->first_name("Jack");$me->last_name("Maney"); You can even set attributes as read-only right out of the box (and an error is thrown if you try to change the value of a read-only attribute), eg has 'ssn'=>(isa=>'Str',is=>'ro'); Also, you can even specify custom getter and setter names via the reader and writer options.Apraxia
While it doesn't appeared to have gained significant traction there is a port which provides a subset of Moose to Python called Bullwinkle: pypi.python.org/pypi/bullwinkleWilton
re: Jack's comment - Here is the AnotherPerson class in Moose. gist.github.com/1782691Wilton
Your AnotherPerson class translated to Perl 6 class AnotherPerson { has Str ($.first-name, $.last-name) is rw } (Moose was based on a early design for classes in Perl 6)Loreeloreen

© 2022 - 2024 — McMap. All rights reserved.