the annoying, verbose self

B

braver

Is there any trick to get rid of having to type the annoying,
character-eating "self." prefix everywhere in a class? Sometimes I
avoid OO just not to deal with its verbosity. In fact, I try to use
Ruby anywhere speed is not crucial especially for @ prefix is better-
looking than self.

But things grow -- is there any metaprogramming tricks or whatnot we
can throw on the self?

Cheers,
Alexy
 
L

Looney, James B

There are always tricks. If 5 characters is really too much to type,
how about 2 characters "s.". Though I would recommend against that
since
it violates standard Python convention.

def foo( self ):

becomes

def foo( s ):

Otherwise, if you happen to be using self.something a lot, just
assign it to a variable, and use that. But be careful as that
can become a lot more difficult to read/maintain than simply
leaving self along to begin with.

ss = self.something
ss.foo()

To me, using 'self' in Python is no different than using some other
variable pointing to a class instance in a static C++ class function.

-James
 
F

Farshid Lashkari

braver said:
Is there any trick to get rid of having to type the annoying,
character-eating "self." prefix everywhere in a class? Sometimes I
avoid OO just not to deal with its verbosity. In fact, I try to use
Ruby anywhere speed is not crucial especially for @ prefix is better-
looking than self.

But things grow -- is there any metaprogramming tricks or whatnot we
can throw on the self?

The most common answer you are going to get is that explicit is better
than implicit, which I tend to agree with. Some people use 's' instead
of 'self'. This shortens the number of characters you have to type, and
is only one character more than the Ruby '@' prefix.

Here is a metaprogramming technique that removes self, but I don't
recommend these sorts of things, especially if other people are going to
be looking at your code in the future. So use it at your own risk!

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362305

-Farshid
 
S

Steven D'Aprano

Is there any trick to get rid of having to type the annoying,
character-eating "self." prefix everywhere in a class?


Oh I know! It' uch a pain. Sinc writing a hug cla lat wk, I'v had a
trribl hortag o lowrca S E L and F charactr. It mak writing vry annoying.

Sometimes I avoid OO just not to deal with its verbosity.

There are other values than brevity. In fact, brevity is one of the less
important values.

In fact, I try to use
Ruby anywhere speed is not crucial especially for @ prefix is better-
looking than self.

Well, it takes all sorts I suppose. Who would those with good taste mock
if everybody liked the same things?

But things grow -- is there any metaprogramming tricks or whatnot we can
throw on the self?

Oh yeah, that's just what I like to see! Complicated, brittle, hard to
debug, difficult to understand metaprogramming tricks in preference to a
simple, easy-to-read naming convention.
 
A

A.T.Hofkamp

You got this highly flexible language, very good for rapid programming, no more
clutter from block brackets and variable declarations, and now this 'self' pops
up.

So much overhead....

Can the computer not decide by itself what I want stored in the object? It can
read my code too!

Oh I know! It' uch a pain. Sinc writing a hug cla lat wk, I'v had a
trribl hortag o lowrca S E L and F charactr. It mak writing vry annoying.

Yes annoying isn't it?

Last week I was programming in C++ again, and now I have this terrible sur-plus
of lowercase T H I and S letters. I don't understand how they do it (I used to,
but not any more).

Maybe we should setup an exchange program so everybody can trade letters with
each other.

There are other values than brevity. In fact, brevity is one of the less
important values.

NO! You got it all wrong here! It is not about brevity, it is about SPEED.

With less letters, there is less to read, so it can be read faster, so it must
be better!

Just like "if x:" is MUCH BETTER than "if x != 0:"


The thing that should be fixed imho, is that the brain of some of us tries to
deduce higher levels of abstractions from what is essentially a very long line
of simple instructions.

Oh yeah, that's just what I like to see! Complicated, brittle, hard to
debug, difficult to understand metaprogramming tricks in preference to a
simple, easy-to-read naming convention.

Maybe we should state first which variables we want to store in self, and then
have a meta-programming hook that automatically puts assignments to those
variables into the object.
And while we are at it, maybe we should also state the type of data we want to
put in it. That should help too.

Now that would be progress.


Ah well, I guess we will have to wait a while before that happens.....
Albert
 
B

bearophileHUGS

Alexy:
Sometimes I
avoid OO just not to deal with its verbosity. In fact, I try to use
Ruby anywhere speed is not crucial especially for @ prefix is better-
looking than self.

Ruby speed will increase, don't worry, as more people will use it.

Bye,
bearophile
 
B

braver


Indeed. Well, my current solution is to bow to the collective wisdom
and retain the self, but type it with just one symbol

..->

.... in TextMate, with the Python bundle! (If only TextMate Python
bundle woulldn't indent everything it pastes.... And that's how Ruby
helps Python -- at the code's very inception TextMate!)

Cheers,
Alexy
 
J

J. Clifford Dyer

You're tilting against windmills. This has been gone over many times. There are very valid reasons for the explicit self, which I understood well enough when I read about them to stop complaining about self, but not well enough to be able to justify to someone else. Sorry for that. But since Alexy likes finding old threads that address his concerns, maybe he'll hunt them down, himself.
You got this highly flexible language, very good for rapid programming, no more
clutter from block brackets and variable declarations, and now this 'self' pops
up.

So much overhead....

Can the computer not decide by itself what I want stored in the object? It can
read my code too!

But not every variable declared inside a class needs to be assigned to self.. Make judicious use of non-self variables, if you don't want to see self everywhere.
Yes annoying isn't it?

Last week I was programming in C++ again, and now I have this terrible sur-plus
of lowercase T H I and S letters. I don't understand how they do it (I used to,
but not any more).

Maybe we should setup an exchange program so everybody can trade letters with
each other.



NO! You got it all wrong here! It is not about brevity, it is about SPEED.

if you're looking for speed of typing, just type a one character self equivalent, like:

class q(object):
def method(;, arg):
;.var = 3

Then when you're done coding: :%s/;/self/g
With less letters, there is less to read, so it can be read faster, so it must
be better!

Ah. Speed of reading. In fact, speed of reading is connected to clarity, not brevity. If you have to keep looking back to some declaration section to remember if a given variable is tied to self, it's going to slow down your comprehension speed. the written chinese language is far more concise than japansese, but it's faster to skim japanese, because of the three alphabet system. Most of the meaning is contained in kanji, while the hiragana supplies disambiguation and grammatical specifiers, so you know you can skip past the hiragana and still retain the basic meaning. Having self used by convention means that once you get used to seeing it, you don't need to read it any more. It would really mess with python coders, though, if each person made up their own self-equivalent. You write "s", I write "self", Larry Wall starts coding python and uses "my". Then we'd all have to actually pay attention, and reading really would slow down. That's probably why self seems to be the most consistently held convention in python. Occasionally, someone will use cls, but that's for a different context, where you really do want people to slow down and realise that something different is going on.
Just like "if x:" is MUCH BETTER than "if x != 0:"
Only when "if x:" is what you mean. The semantics are different:

py>>> x = ''
py>>> if x: print "x"
py>>> if x != 0: print "x != 0"
x != 0
The thing that should be fixed imho, is that the brain of some of us tries to
deduce higher levels of abstractions from what is essentially a very long line
of simple instructions.

Sorry, no entiendo. What needs to be fixed here?
Maybe we should state first which variables we want to store in self, and then
have a meta-programming hook that automatically puts assignments to those
variables into the object.
And while we are at it, maybe we should also state the type of data we want to
put in it. That should help too.

Now that would be progress.

I hope you are taking the piss.
Ah well, I guess we will have to wait a while before that happens.....
Albert

Oh God. You are taking the piss. IHBT.

<sigh>
 
C

Colin J. Williams

Alexy:

Ruby speed will increase, don't worry, as more people will use it.

Bye,
bearophile

I don't see this as a big deal, but
suppose that the syntax were
expanded so that, in a method, a dot
".", as a precursor to an identifier,
was treated as "self." is currently treated?

References to the instance itself would
continue to use "self". A lonely
dot would get lost on the page.

Initially, this form could be treated as
an alternative, usage would
determine its fate. Thus "self.name" or
".name" would identify the same
object.

Colin W.
 
C

Colin J. Williams

Alexy:

Ruby speed will increase, don't worry, as more people will use it.

Bye,
bearophile

I don't see this as a big deal, but
suppose that the syntax were
expanded so that, in a method, a dot
".", as a precursor to an identifier,
was treated as "self." is currently treated?

References to the instance itself would
continue to use "self". A lonely
dot would get lost on the page.

Initially, this form could be treated as
an alternative, usage would
determine its fate. Thus "self.name" or
".name" would identify the same
object.

Colin W.
 
A

Ayaz Ahmed Khan

braver said:
Is there any trick to get rid of having to type the annoying,
character-eating "self." prefix everywhere in a class? Sometimes I
avoid OO just not to deal with its verbosity. In fact, I try to use
Ruby anywhere speed is not crucial especially for @ prefix is better-
looking than self.

I've never really understood why some people find that annoying to do. I
make it a point to use, for example, the `this` operator when writing C++
code to avoid implicilty calling/accessing attributes of objects as much
as possible.
 
B

Bruno Desthuilliers

Colin J. Williams a écrit :
I don't see this as a big deal, but suppose that the syntax were
expanded so that, in a method, a dot ".", as a precursor to an identifier,
was treated as "self." is currently treated?

<dead-horse-beaten-to-hell-and-back>

Python's "methods" are thin wrapper around functions, created at lookup
time (by the __get__ method of the function type). What you define in a
class statement are plain functions, period. So there's just no way to
do what you're suggesting.

</dead-horse-beaten-to-hell-and-back>
 
K

Kay Schluehr

Colin J. Williams a écrit :





<dead-horse-beaten-to-hell-and-back>

Python's "methods" are thin wrapper around functions, created at lookup
time (by the __get__ method of the function type). What you define in a
class statement are plain functions, period. So there's just no way to
do what you're suggesting.

</dead-horse-beaten-to-hell-and-back>

The object model is irrelevant here. The substitution is purely
syntactical and gets resolved at compile time:

def foo(first, ...):
.bar = ...

is always equivalent with:

def foo(first, ...):
first.bar = ...

and generates the same bytecode.

Whether this is helpfull, beautifull or necessary is another issue.

Kay
 
P

Paul Boddie

I've never really understood why some people find that annoying to do. I
make it a point to use, for example, the `this` operator when writing C++
code to avoid implicilty calling/accessing attributes of objects as much
as possible.

Precisely. One wonders whether the people complaining so vehemently
about self have ever encountered coding style guides.

Paul
 
B

Bruno Desthuilliers

Kay Schluehr a écrit :
(snip)
The object model is irrelevant here. The substitution is purely
syntactical and gets resolved at compile time:

def foo(first, ...):
.bar = ...

is always equivalent with:

def foo(first, ...):
first.bar = ...

and generates the same bytecode.

Point taken. But:
Whether this is helpfull, beautifull or necessary is another issue.

indeed.
 
B

Bruno Desthuilliers

Paul Boddie a écrit :
Precisely. One wonders whether the people complaining so vehemently
about self have ever encountered coding style guides.

Like the one mandating to prefix "member variables" with 'm_' ?-)
 
B

braver

about self have ever encountered coding style guides.

Dude, I'm also programming in Ada, 83 to 95 to 2005. Beautiful
language, a living style guide. I love typing names dozens of
charactares long -- in Ada. Ada has scope control, separate
compilation, renames, overloading, types, etc... However, in
scripting languages, it's not cool, and I'd just love to see self hide
for a bit of a change -- it's a nuisance after Ruby, 's all. Nothing
eternal or worth assembling a NASA panel or Python foundation meeting,
just a li'l respite to make a tiny script more lucid, OK?

Peace,
Alexy
 
P

Paul Boddie

Dude, I'm also programming in Ada, 83 to 95 to 2005.

It's not often that I get called "dude". ;-)
Beautiful language, a living style guide.

Beautiful plumage! [*]
I love typing names dozens of
charactares long -- in Ada. Ada has scope control, separate
compilation, renames, overloading, types, etc... However, in
scripting languages, it's not cool, and I'd just love to see self hide
for a bit of a change -- it's a nuisance after Ruby, 's all. Nothing
eternal or worth assembling a NASA panel or Python foundation meeting,
just a li'l respite to make a tiny script more lucid, OK?

Well, it's just a pragmatic decision which exposes the mechanism of
passing the instance, which is typically hidden in most of the other
object-oriented languages. The issue is how you resolve names without
having specific details of which names exist on an object. Consider
this:

class X:
def f(value): # in "Selfless Python"!
attr = value

What is attr? A local, a class attribute or an instance attribute?
Sure, we could deduce that f is an instance method of X, and that attr
could really be "self.attr" or even "X.attr". Languages like Java
remove such uncertainty by forcing the declaration of locals and class
and instance attributes, but Python has no such restrictions - an
instance attribute called attr might be introduced later in such a
program, outside any function or method clearly related to the class,
and we'd need to know about that to make an informed decision in cases
like the one shown above.

Paul

[*] Sorry, but such an exclamation is almost obligatory under the
circumstances.
 
K

Kay Schluehr

Colin said:
I had never thought of trying the above, which is, essentially what I was
suggesting, as the syntax specifies:

primary ::=
atom | attributeref
| subscription | slicing | call

attributeref ::=
primary "." identifier

I did try it and get:

# tmp.py
class Z():
def __init__(self):
a= 1
self.b= 2
#.c= 3 Marked as a syntax error by PyScripter

def y(self):
self.a= 4
#.b= 5 Marked as a syntax error by PyScripter

It seems that some, probably simple, change in the parsing is needed.

Colin W.

Sure. Since you cite the grammar let me say that I find it somewhat
confusing that the grammar in the Python documentation doesn't
correspond to the grammar used by the CPython parser. For the following
I will use the notations of the Grammar file used by the CPython parser.

In order to adapt the syntax take a look at

atom: ('(' [yield_expr|testlist_gexp] ')' |
'[' [listmaker] ']' |
'{' [dictmaker] '}' |
'`' testlist1 '`' |
NAME | NUMBER | STRING+)

The last row must be changed to

['.'] NAME | NUMBER | STRING+)
~~~~~

But then you run into conflict with the definition of the ellipsis in rule

subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]

because you need two token of lookahead. Pythons LL(1) parser might not
manage this.

This problem vanishes with Python 3.0 which defines an own ellipsis literal:

atom: ('(' [yield_expr|testlist_comp] ')' |
'[' [testlist_comp] ']' |
'{' [dictorsetmaker] '}' |
NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')

Kay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,162
Latest member
GertrudeMa
Top