Python Newbie

C

Chris Angelico

Hi guys,

Question. Have this code

intX = 32 # decl + init int var
intX_asString = None # decl + init with NULL string var

intX_asString = intX.__str__ () # convert int to string

What are these ugly underscores for? _________________str___________________

Normally you don't need them. Write it this way:

intX_asString = str(intX)

The "dunder" methods ("d"ouble "under"score, leading and trailing),
also called "magic methods", are the implementations of various
special features. For instance, indexing foo[1] is implemented using
the __getitem__ method. Here's a list:

http://docs.python.org/3.3/reference/datamodel.html#special-method-names

You'll seldom, if ever, call these methods directly.

By the way, when you're asking a completely new question, it usually
helps to do so as a brand new thread (not a reply) and with a new
subject line. Otherwise, you risk people losing the new question among
the discussion of the old.

ChrisA
 
R

Roy Smith

Chris Angelico said:
The "dunder" methods ("d"ouble "under"score, leading and trailing),
also called "magic methods", are the implementations of various
special features. For instance, indexing foo[1] is implemented using
the __getitem__ method. Here's a list:

http://docs.python.org/3.3/reference/datamodel.html#special-method-names

You'll seldom, if ever, call these methods directly.

On the other hand, once you get into building your own classes, you will
often be *writing* them. The most common are __str__(), __repr__(), and
__unicode__(), and of course, __init__().

A quick look over my current project shows 471 classes, and I've defined:

1 __del__
1 __getattr__
1 __iter__
1 __new__
2 __cmp__
2 __len__
3 __ne__
4 __contains__
9 __eq__
14 __str__
38 __unicode__
62 __repr__
140 __init__

Not to mention the boilerplate:

if __name__ == '__main__":

which shows up all over the place.
 
D

Dennis Lee Bieber

All apps that return an error code to the operating system return 0 for
success, any other value for error. All command-line utilities work
this way, all shells, etc. Even Windows command-line apps work this way
(errorlevel is what they call it).

Decided to look up the VAX/VMS scheme...

"""
If you know the condition code for a message, you can use F$MESSAGE to
translate the code to its associated message. For example:
$ WRITE SYS$OUTPUT F$MESSAGE(%X00000001)
%SYSTEM-S-NORMAL, normal successful completion
"""

VMS used a status of "1" for normal success (which implies that all
the odd integers were success/info messages, even integers would be
warning/error/fatal.

http://h71000.www7.hp.com/doc/73final/documentation/pdf/ovms_msg_ref_al.pdf
 
D

Dennis Lee Bieber

:) Yep. It ended up feeling a little contrived, and I should have
changed the word "awesome" before it once "Awesome" got into the
acronym, but yeah, that was deliberate.

Good -- I'd hate to think I was reading in hidden meanings that
weren't really there.
 
S

Steven D'Aprano

Hi guys,

Question. Have this code

intX = 32 # decl + init int var
intX_asString = None # decl + init with NULL string var

intX_asString = intX.__str__ () # convert int to string

What are these ugly underscores for?
_________________str___________________


To demonstrate that the person who wrote this code was not a good Python
programmer. I hope it wasn't you :) This person obviously had a very
basic, and confused, understanding of Python.

And, quite frankly, was probably not a very good programmer of *any*
language:

- poor use of Hungarian notation for variable names;
- pointless pre-declaration of values;
- redundant comments that don't explain anything.

If that code came from the code-base you are maintaining, no wonder you
don't think much of Python! That looks like something I would expect to
see at the DailyWTF.

http://thedailywtf.com/


The above code is better written as:

x = 32
x_asString = str(x)


Double-underscore methods are used for operator overloading and
customizing certain operations, e.g. __add__ overloads the + operator.
You might define a class with a __str__ method to customize converting
the object to a string:

# Toy example.
class MyObject:
def __str__(self):
return "This is my object"


But you would not call the __str__ method directly. (I won't say "never",
because there are rare, advanced, uses for calling double-underscore
methods directly.) You would use a public interface, such as the str()
function.
 
M

Michael Torrie

Decided to look up the VAX/VMS scheme...

"""
If you know the condition code for a message, you can use F$MESSAGE to
translate the code to its associated message. For example:
$ WRITE SYS$OUTPUT F$MESSAGE(%X00000001)
%SYSTEM-S-NORMAL, normal successful completion
"""

VMS used a status of "1" for normal success (which implies that all
the odd integers were success/info messages, even integers would be
warning/error/fatal.

http://h71000.www7.hp.com/doc/73final/documentation/pdf/ovms_msg_ref_al.pdf

It's interesting to note that Windows NT sort of descends from VMS. I
guess the end result was an unholy blend of VMS and CP/M.
 
G

Grant Edwards

It's worth noting, though, that there are self-perpetuating aspects to
it. I can happily distribute a .py file to a Linux audience, because
many Linux distros come with a Python already installed, or at very
least can grab one easily via the package manager.

Are there any popular, mainstream Linux distros that don't come with
Python installed by default?

RedHat has had Python installed as part of the base system since day
1, since both the installer and some of the system admin stuff was
written in Python. I always thought RPM also originally written in
Python, but can't find any references. In any case, yum is written in
Python, so I doubt there are any RPM-based distros that don't have
Python as part of a base install.

Python is required by Gentoo, since the package management tools are
written (at least partially) in Python. In theory, it might be
possible to do an install tha doesn't include Python by using a
different package-management system, but in practice Python is always
there on Gentoo systems.

All of the Debian systems I've seen had Python installed, but I'm not
sure how "required" it is.

AFAICT, Python is installed as part of all Ubuntu installations as
well.
 
P

piterrr.dolinski

To demonstrate that the person who wrote this code was not a good Python
programmer. I hope it wasn't you :) This person obviously had a very

basic, and confused, understanding of Python.



And, quite frankly, was probably not a very good programmer of *any*

language:



- poor use of Hungarian notation for variable names;

- pointless pre-declaration of values;

- redundant comments that don't explain anything.



If that code came from the code-base you are maintaining, no wonder you

don't think much of Python! That looks like something I would expect to

see at the DailyWTF.

Hi. Steve, I don't know where you have been over the past couple of days but it is widely known (if the thread title is any indication) that I am indeed very new to Python, but not new to programming in general.

To give a bit of background where I found __str__, I am using a Python IDE called PyScripter. Its Intellisense is full of methods starting and ending with "__", hence the question.

Regarding Hungarian notation, I don't use it in any other language but Python and JS. Call it poor, but it helps me to remember what type a variable is. The redundant comments serve the same purpose. As for "pointless predeclaration", it helps me know where in the code I first started using the variable, so I know there are no references to it before then.

Peter
 
P

piterrr.dolinski

if (some statement): # short form
What all those ugly brackets are for?

Mark,

Back in the day when C was king, or take many newer long established languages (C#, Java), the use of () has been widespread and mandated by the compilers. I have never heard anyone moan about the requirement to use parentheses. Now come Python in which parens are optional, and all of a sudden they are considered bad and apparently widely abandoned. Do you really not see that code with parens is much more pleasing visually? I could understand someone's reluctance to use parens if they are very new to programming and Pythons is their first language. But my impression here is that most group contributors are long-time programmers and have long used () where they are required. Again, I'm really surprised the community as a whole ignores the programming "heritage" and dumps the parens in a heartbeat.

Peter
 
P

piterrr.dolinski

if (some statement): # short form
What all those ugly brackets are for?

Mark,

Back in the day when C was king, or take many newer long established languages (C#, Java), the use of () has been widespread and mandated by the compilers. I have never heard anyone moan about the requirement to use parentheses. Now come Python in which parens are optional, and all of a sudden they are considered bad and apparently widely abandoned. Do you really not see that code with parens is much more pleasing visually? I could understand someone's reluctance to use parens if they are very new to programming and Pythons is their first language. But my impression here is that most group contributors are long-time programmers and have long used () where they are required. Again, I'm really surprised the community as a whole ignores the programming "heritage" and dumps the parens in a heartbeat.

Peter
 
M

Mitya Sirenef

Mark,

Back in the day when C was king, or take many newer long established
languages (C#, Java), the use of () has been widespread and mandated
by the compilers. I have never heard anyone moan about the requirement
to use parentheses. Now come Python in which parens are optional, and
all of a sudden they are considered bad and apparently widely
abandoned. Do you really not see that code with parens is much more
pleasing visually? I could understand someone's reluctance to use
parens if they are very new to programming and Pythons is their first
language. But my impression here is that most group contributors are
long-time programmers and have long used () where they are required.
Again, I'm really surprised the community as a whole ignores the
programming "heritage" and dumps the parens in a heartbeat.

Peter


When I write in English, I write: If it rains, I'll get an umbrella.
I do not write: If (it rains), I'll get an umbrella. The second example
isn't any clearer. The only reason you like unneeded parens is that
you're used to them. I've never heard of anyone missing this "feature"
after a month or two of using Python.

-m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The world is a perpetual caricature of itself; at every moment it is the
mockery and the contradiction of what it is pretending to be.
George Santayana
 
C

Chris Angelico

Are there any popular, mainstream Linux distros that don't come with
Python installed by default?

Probably all the main desktop distros come with _some_ Python (but not
necessarily a recent one... RHEL with 2.4?!). I used "many" rather
than "all" in case there's one somewhere that doesn't, but even then,
Python will be an easily-added feature.

ChrisA
 
M

Michael Ross

Mark,

Back in the day when C was king, or take many newer long established
languages (C#, Java), the use of () has been widespread and mandated by
the compilers. I have never heard anyone moan about the requirement to
use parentheses.

You've never heard me then. I ... "strongly dislike" having to parse
visual elements which I consider superfluous and implicit.

Does the English language have a proverb like "not being able to see the
forest for the trees"?

To me, a C source looks like all brackets. Can't see the code for all the
brackets.

Now come Python in which parens are optional, and all of a sudden they
are considered bad and apparently widely abandoned. Do you really not
see that code with parens is much more pleasing visually?

I guess one can get just as religious about the brackets as one can about
the whitespace.


if ( condition ) { action }
vs
if condition: action


In time estimated, I'd say I can read and understand Python code about 20%
faster than any of these brackety languages, even compared to languages I
worked a with couple of years longer. That's a lot of effort saved.



Michael
 
E

Ethan Furman

Back in the day when C was king, or take many newer long established languages (C#, Java), the use of () has been widespread and mandated by the compilers. I have never heard anyone moan about the requirement to use parentheses. Now come Python in which parens are optional, and all of a sudden they are considered bad and apparently widely abandoned. Do you really not see that code with parens is much more pleasing visually? I could understand someone's reluctance to use parens if they are very new to programming and Pythons is their first language. But my impression here is that most group contributors are long-time programmers and have long used () where they are required. Again, I'm really surprised the community as a whole ignores the programming "heritage" and dumps the parens in a heartbeat.

Python will also allow you to have ';' at the end of your lines. It does nothing for you, but perhaps you also find
that "visually pleasing"?

I find () to be four extra keystrokes, not visually pleasing, and needed only to override order of operations.

One of the things I love about Python is its ability to get out of the way and let me work:

- no variable declarations, just use 'em
- no type declarations, just use 'em
- no need to remember what's an object and what's not -- everything is an object
- no need to cast to bool as everything has a truthy/falsey (something vs nothing) value


From a different email you said PyScripter was showing you all the dunder methods? You might want to try one of the
others.
 
M

MRAB

Mark,

Back in the day when C was king, or take many newer long established
languages (C#, Java), the use of () has been widespread and mandated
by the compilers. I have never heard anyone moan about the
requirement to use parentheses. Now come Python in which parens are
optional, and all of a sudden they are considered bad and apparently
widely abandoned. Do you really not see that code with parens is much
more pleasing visually? I could understand someone's reluctance to
use parens if they are very new to programming and Pythons is their
first language. But my impression here is that most group
contributors are long-time programmers and have long used () where
they are required. Again, I'm really surprised the community as a
whole ignores the programming "heritage" and dumps the parens in a
heartbeat.
Some languages require parentheses, others don't.

C does. C++, Java and C# are descended from, or influenced by, C.

Algol didn't (doesn't?). Pascal, Modula-2, Oberon, Ada, and others
don't.

Parentheses are used where required, but not used where they're not
required, in order to reduce visual clutter.
 
M

Mark Lawrence

Mark,

Back in the day when C was king, or take many newer long established languages (C#, Java), the use of () has been widespread and mandated by the compilers. I have never heard anyone moan about the requirement to use parentheses. Now come Python in which parens are optional, and all of a sudden they are considered bad and apparently widely abandoned. Do you really not see that code with parens is much more pleasing visually? I could understand someone's reluctance to use parens if they are very new to programming and Pythons is their first language. But my impression here is that most group contributors are long-time programmers and have long used () where they are required. Again, I'm really surprised the community as a whole ignores the programming "heritage" and dumps the parens in a hea
rtbeat.

Peter

Your words "the use of () has been widespread and mandated by the
compilers" and "have long used () where they are required". As they are
neither mandated nor required in Python it just wastes the time of
anybody reading code as they have to parse something that offers nothing
except visual noise. As for being "visually pleasing" that's simply
laughable. I want to be able to read code, not hang it in an art gallery.
 
C

Chris Angelico

Some languages require parentheses, others don't.

C does. C++, Java and C# are descended from, or influenced by, C.

Algol didn't (doesn't?). Pascal, Modula-2, Oberon, Ada, and others
don't.

Parentheses are used where required, but not used where they're not
required, in order to reduce visual clutter.

And just to muddy the waters, parens are used in Python when the
condition goes over a line break:

if (condition1
and condition2
and condition3):

ChrisA
 
R

Roy Smith

Chris Angelico said:
And just to muddy the waters, parens are used in Python when the
condition goes over a line break:

if (condition1
and condition2
and condition3):

ChrisA

That could also be written:

if condition1 \
and condition2 \
and condition3:

but as a practical matter, I would write it in the parens style, if for
no other reason than because emacs does a better job of auto-indenting
it that way :)
 

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,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top