Syntax across languages

Alex Martelli aleaxit at yahoo.com
Sun Oct 23 13:08:44 EDT 2005


<bearophileHUGS at lycos.com> wrote:
   ...
> - Information about the current line and file as Ruby:
> __LINE__ __FILE__
> Instead of the python version:
> inspect.stack()[0][2] inspect.stack()[0][1]

__file__ is around in Python, too, but there's no __line__ (directly).

> - identity function: "identity" as in Common Lisp (probably of little
> use in Python).

I've seen enough occurrences of "lambda x: x" in Python code with a
generally functional style that I'd love to have operator.identity (and
a few more trivial functions like that) for readability;-)

> - object cloning: obj.copy()  obj.deepcopy()

Like (say) container.length() versus len(container), I'm perfectly
comfortable relying on functions rather than methods.  It even makes it
easier to allow several alternative ways for an object to provide such
functionality (e.g. by implementing __getstate__ and maybe __setstate__
as opposed to __copy__ and maybe __deepcopy__) -- which would be
feasible even with a method, of course (Template Method DP), but IS
easier when relying on functions (and operators).

> - accessing parent method:
> super as in Ruby, instead as in Python:
> super(Class, self).meth(args)

Ruby's syntax may be better for a single-inheritance language, but
Python's, while less elegant, may be more appropriate in the presence of
multiple inheritance.

> - recursive "flatten" as in Ruby (useful)

Usage too rare to deserve a built-in method, IMHO, considering the ease
of coding the equivalent:

def flatten(x):
    if not isinstance(x, list): yield x
    for y in x: yield flatten(y)

What I _do_ envy Ruby's syntax, a little, is the convention of ending
methodnames with exclamation mark to indicate "modifies in-place" (and,
secondarily, question mark to indicate predicates).  The distinction
between, e.g.,
    y = x.sort()
and
    x.sort!()
in Ruby is much clearer, IMHO, than that between, say,
    y = sorted(x)
and
    x.sort()
in Python...


Alex



More information about the Python-list mailing list