Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Allie
Jan 17, 2004

The two print forms aren't compatible with each other. If you want to target both 2.x and 3.x, you should write code for 2.x and use the upcoming 2to3 script to translate it to 3.x code.

The beta schedule for 2.6 and 3.0 is nearing to a close. As far as I know, the releases are still on track for October.

Adbot
ADBOT LOVES YOU

bitprophet
Jul 22, 2004
Taco Defender

Milde posted:

The two print forms aren't compatible with each other.

...they aren't?
code:
jforcier@sunner ~ $ python
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print "foo"
foo
>>> print("foo")
foo
>>>
Not snarking -- but I've seen/used both interchangeably without problems, at least on 2.5. What do you mean by "aren't compatible"?

Chin Strap
Nov 24, 2002

I failed my TFLC Toxx, but I no longer need a double chin strap :buddy:
Pillbug

Milde posted:

The beta schedule for 2.6 and 3.0 is nearing to a close. As far as I know, the releases are still on track for October.

Wait, could someone explain this? Are 2.6 and 3.0 set for the same release times? I'm confused :(

Allie
Jan 17, 2004

The only reason it works is because the parentheses have no meaning your example. They make tuples when you insert a comma, and you probably don't mean to print a tuple if you're using the print statement with multiple arguments. The print statement also has special syntax for printing to specific file objects, using the >> operator. This is gone in 3.0.

There are more changes than just that. Look at the what's new page for Python 3.0. Try running the 3.0 print examples in your 2.5 prompt - most won't work. When writing code for 2.x you should write 2.x code. If you're trying to target both platforms, the 2to3 script will take care of this, making the whole effort pointless.

hey mom its 420
May 12, 2007

code:
>>> print('hehe', 'hahaha')
('hehe', 'hahaha')
>>> print 'hehe', 'hahaha'
hehe hahaha
edit: ugh, beaten, gently caress you milde

Allie
Jan 17, 2004

Chin Strap posted:

Wait, could someone explain this? Are 2.6 and 3.0 set for the same release times? I'm confused :(

Yes. They're two branches of Python, each with their own ongoing development. They're being released in tandem because 2.6 has a lot of features backported from 3.0. It's sort of a stepping stone to 3.0, making it easier to write code that can be automatically translated for 3.0 with 2to3.

I wouldn't worry about either of them right now for day-to-day development. Wait until you have a reason to upgrade, and be sure whatever tools or libraries you use are available for the version you want to move to.

If you develop libraries or software that other people use, then you might want to pay attention and see if porting code is a good idea. :)

Allie fucked around with this message at 03:12 on Aug 21, 2008

fritz
Jul 26, 2003

Milde posted:

The two print forms aren't compatible with each other.

This is such a bogus change. Old print never hurt nobody.

bitprophet
Jul 22, 2004
Taco Defender

Bonus posted:

code:
>>> print('hehe', 'hahaha')
('hehe', 'hahaha')
>>> print 'hehe', 'hahaha'
hehe hahaha
edit: ugh, beaten, gently caress you milde

Hrm, between this and Milde's explanation I guess I'm a noob or something when it comes to printing; I never, ever do print x, y, instead doing either print "%s %s" % (x, y) or print " ".join([x, y]) (obviously for varying numbers of strings, not just two). I also never use the >> operator, instead opting for the more obvious (for me) fileobject.write("foo").

All that aside, I get your point, the semantics are obviously changing in a more complicated way than in my original example, rendering it moot. And I never intended to say that one should not use 2to3 -- you certainly should.

Finally, as has sort of been implied, someone who's new enough that they need to ask about different import styles probably shouldn't seriously worry about futureproofing (not trying to put down Panic!).


Also, speaking of 2.6/3.0, looks like the final betas just came out. Yay :) Wish I was following this stuff more closely, but not using Python 100% of the time in my job has made me slack off a bit.

Scaevolus
Apr 16, 2007

from http://python.org/download/releases/2.6/NEWS.txt
code:
- Keyword arguments can now follow starred arguments. (``f(a, *args,
  keyword=23)`` is now valid syntax.)
:woop:

ahobday
Apr 19, 2007

fritz posted:

This is such a bogus change. Old print never hurt nobody.

I thought the same thing as soon as I heard it, but making print act like a function call makes the language more consistent. When everything else is based off the foo() approach, having bar "" is a little weird.

hey mom its 420
May 12, 2007

Check out this video http://video.google.com/videoplay?docid=-6459339159268485356&ei=CEOtSMOwHZCuigKD_qjpDg&q=python+3000+guido at approximately 50 minutes and 30 seconds where Guido talks about turning print into a function, how most people hated it at first, but he gives a nice reasoning as to why it's being done.

Lurchington
Jan 2, 2003

Forums Dragoon
As soon as he referred to being forced to manually converting print statements to logging functions I was sold.

hey mom its 420
May 12, 2007

The best thing is though, you won't even have to run a search and replace to change it to logging or whatever. You can just do something like print = Logging.log

m0nk3yz
Mar 13, 2002

Behold the power of cheese!
Yes, right now (provided I stop breaking the build) the 2.6 and 3.0 releases are "on track"

Download and test the latest betas people!

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

dense vegetation posted:

I've looked at a couple of Python books / resources, namely Mark Lutz - Learning Python, Swaroop C. H. - A Byte Of Python and I'm not satisfied. If anyone has ever read Kochan's Programming in C you'll know what I'm looking for. I find a lot of the stuff so far presented to me a bit too "scatty" and assuming prior knowledge of Java / C / C++, which, although I am very familiar with the C syntax, I don't want.

http://diveintopython.org/ is usually what's quoted on comp.lang.python when this question comes up. It's really well organized and I picked python up in a day or two after reading it.

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

Hey, I'm a python and programming newbie, I've been going through some newbie tutorials, just getting a feel for whats going on. I'm just wondering if someone could explain to me how calling a function and using it is working here:

code:
import time
# Create daily menu based on MENU.TXT
# First open the files to read(r) and write(w)
inp = open("menu.txt","r")
outp = open("menu.prn","w")


# Create todays date string 
today = time.localtime(time.time())
theDate = time.strftime("%A %B %d", today)

# Add Banner text and a blank line
outp.write("Menu for %s\n\n" % theDate) 

# copy each line of menu.txt to new file
for line in inp:
    outp.write(line)

print "Menu created for %s..." % theDate

# Now close the files
inp.close()
outp.close()
I apologise for the newbieness, when we're creating todays date string, one line says "today = time.localtime(time.time())". I understand we're creating a variable and we're using the localtime function, what I don't get exactly is the time. before it and the time.time() inside the function. The tutorial didn't really explain what's going on here, can somebody help me with just a quick human explanation. I want to make sure I understand everything fully instead of glossing over this and missing something key :)

tef
May 30, 2004

-> some l-system crap ->

LuckySevens posted:

code:
import time

today = time.localtime(time.time())
theDate = time.strftime("%A %B %d", today)
What I don't get exactly is the time. before it and the time.time() inside the function.

time is a module. you did import time at the top of your program.

Inside of the time module, there are a number of functions, including 'time', 'localtime' and 'strftime'

So, in your program 'time' means a reference to the time module, and 'time.time' means the time function inside of the time module


code:
>>> import time
>>> time 
<module 'time' from '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload/time.so'>
>>> dir(time)
['__doc__', '__file__', '__name__', 'accept2dyear', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']
>>> time.time()
1219910575.051717

Grey Area
Sep 9, 2000
Battle Without Honor or Humanity
LuckySevens:

First, we have this line: import time
This loads the time module, making its contents available in your program. The time module is a standard part of Python and is documented here. The module is actually a python file, time.py, in the Python installation directory. To access its contents you have to prefix them with the name of the module.

Now we look at this line: today = time.localtime(time.time())

In this line we are calling two functions in the time module:
[list=1]
[*]time.time() - returns the current time as a number that corresponds to the computers internal clock. (The meaning of the number depends on your operating system, but it's usually the number of seconds since the start of 1970 (universal time).)
[*]time.localtime() - converts the timestamp returned by time.time() into a nine-element tuple containing a more useful representation of the time in your timezone. (A tuple is like a read-only list.) The tuple contains the following: (year, month, day_of_month, hour, minute, second, day_of_week, day_of_year, is_dst) The exact meaning of these values are in the time module docs.
[/list]
Because the call to time.time() occurs inside the call to time.localtime() it is passed directly from one to the other without being stored in a variable.

In the following line, theDate = time.strftime("%A %B %d", today) the tuple from time.localtime() is converted into a human-readable string by the time.strftime() function. The first parameter is a string that specifies the desired format of the date string. Here %A will be replaced with the name of the weekday, %B by the name of the month and %d by the day of the month. (The names will depend on your OS language setting.) In English the output for today would be "Thursday August 28".

edit: fb, should have hit submit before coffee break.

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

Thanks guys, Grey Area that's an awesome explanation and exactly what I was looking for, much thanks for taking the time to type it :)

ahobday
Apr 19, 2007

Is there a beginner-friendly reference to the best way to structure Python programs? For example, you could put your main code, where the program starts, just straight into the base Python file, but I see a lot of people defining a main function and then using "if __name__ == __main__ then main()" or whatever it is. I'm not sure why they do that, but I'd prefer to do it if it's a better method.

So is there some kind of reference that I can use that'll show me the best way to structure in this sense? When to use multiple source files, what to put into functions, that sort of thing?

Bozart
Oct 28, 2006

Give me the finger.

Centipeed posted:

but I see a lot of people defining a main function and then using "if __name__ == __main__ then main()" or whatever it is. I'm not sure why they do that, but I'd prefer to do it if it's a better method.


They do that because it makes turning your python files into libraries of functions really easy. All you have to do is import them and you get all of their classes and functions, without having to run the code in the main part.

duck monster
Dec 15, 2004

Man. I should one of these days, sit down and write a tutorial for absolute programming newbies.

illamint
Jun 26, 2005

According to The Oxford English Dictionary, the word "snapshot" was originally a hunting term.
So, I'm running a DC hub for a few friends of mine, and I'm able to extend it by loading in Python scripts which the hub runs in an internal Python interpreter instance. I'm trying to write a python script using SimpleXMLRPCServer so that I can query hub status remotely, and I can't figure out how to properly thread it. I need to be able to programmatically terminate the entire Python script by itself, including the running SimpleXMLRPCServer thread. I've gotten to the point now where I've subclassed SimpleXMLRPCServer to allow me to terminate the serve_forever() loop (I think), but I guess it doesn't terminate fast enough, because even if I call os._exit() when I try to unload the Python script, the entire app crashes via this error: "Py_EndInterpreter: not the last thread". I can't fork(), because doing so forks the entire hub app (Verlihub), and I can't think of any other way to do this, since I need to pass a reference to the Verlihub python instance. Is there a better way to be doing this?

Bodhi Tea
Oct 2, 2006

seconds are secular, moments are mine, self is illusion, music's divine.
What's the best way for me to check unread messages in the gmail inbox and get the 'From' and 'Subject' of each one?

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

illamint posted:

I've gotten to the point now where I've subclassed SimpleXMLRPCServer to allow me to terminate the serve_forever() loop (I think), but I guess it doesn't terminate fast enough, because even if I call os._exit() when I try to unload the Python script, the entire app crashes via this error: "Py_EndInterpreter: not the last thread".

You need to call "wait" or "join" on the thread after you terminate it. That will cause the app to pause until the thread is finished cleaning itself up.

Bodhi Tea posted:

What's the best way for me to check unread messages in the gmail inbox and get the 'From' and 'Subject' of each one?

Connect through IMAP and make sure you don't have it set to delete items after downloading. (See the imaplib library - I'm sure you can find better docs on Google.)

JoeNotCharles fucked around with this message at 04:15 on Sep 3, 2008

Bozart
Oct 28, 2006

Give me the finger.
I don't know if anyone has mentioned this yet, but http://code.google.com/p/soc/wiki/PythonStyleGuide is pretty useful in terms of both examples and explanations of style. Some people might be annoyed by the two space tab instead of four space tab, but you can always ignore that.

bitprophet
Jul 22, 2004
Taco Defender

Bozart posted:

I don't know if anyone has mentioned this yet, but http://code.google.com/p/soc/wiki/PythonStyleGuide is pretty useful in terms of both examples and explanations of style. Some people might be annoyed by the two space tab instead of four space tab, but you can always ignore that.

Wonder what reason they have to diverge from the official Python style guide, PEP 8?

hey mom its 420
May 12, 2007

I'll never get why people make their own style guidelines when there's good old PEP 8.

Bozart
Oct 28, 2006

Give me the finger.

bitprophet posted:

Wonder what reason they have to diverge from the official Python style guide, PEP 8?

Probably a combination of not wanting to look like tabs (can't confuse 2 spaces for a tab character), reserving 4 space indents for line continuations, and a compromise between keeping lines at or below 80 characters and keeping things compact.

Anyway the reason I mention it is because it says things like

always have an
code:
if __name__ == "__main__"
    main()
and why it is good to have it (and PEP doesn't mention this at all)
and decorators, which PEP doesn't mention at all


there might be other stuff. I just figured it would be useful to mention a different perspective. I only found out about it from reading the ABCs of Python interviewy thing:
http://www.techworld.com.au/article/255835/-z_programming_languages_python?pp=5

and then I figured it might some insight because it is used so heavily by Google and Guido van Rossum works there, and he coauthored the PEP 8.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Bozart posted:

and then I figured it might some insight because it is used so heavily by Google and Guido van Rossum works there, and he coauthored the PEP 8.

GvR made Python, and I am pretty sure he's whined about python code in Google before (they also use 90% old style classes even on new code).

Bozart
Oct 28, 2006

Give me the finger.

deimos posted:

GvR made Python, and I am pretty sure he's whined about python code in Google before (they also use 90% old style classes even on new code).

Well they say to use new style classes inheriting from object in the style guide.

It isn't like I'm going to use their stuff exactly, it is more for learning a couple different ways to think about the pros and cons. Then again in this case their style is almost identical to PEP 8. v:)v

bitprophet
Jul 22, 2004
Taco Defender

Bozart posted:

and why it is good to have it (and PEP doesn't mention this at all)
and decorators, which PEP doesn't mention at all

Yea, PEP8 (note: don't just call it PEP, there's far more than one PEP! :)) could theoretically be extended with more guidelines, although then again given Guido's penchant for keeping stuff simple, maybe not. I'd still like to see it updated or another PEP added as an addendum with "extra guidelines".

You know, trying to document what it means to be "Pythonic", sorta like that site I probably have bookmarked but can't find right now (guy has a nice big list of Python idioms and what to do / not do).

Benji the Blade
Jun 22, 2004
Plate of shrimp.

bitprophet posted:

You know, trying to document what it means to be "Pythonic", sorta like that site I probably have bookmarked but can't find right now (guy has a nice big list of Python idioms and what to do / not do).

I think this is what you're referring to: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html. It's an excellent guide for people who've got the Python syntax down but aren't quite thinking in Python yet.

The Google Python standards are generally pretty good, but contradicting PEP 8 by suggesting two spaces instead of four is, in my mind, a terrible idea. It may work well inside Google considering they have a whole lot of in-house code, but when you're programming by yourself or in a small team, this is just going to cause a lot of headaches. The problem is not stylistic, like it would be in C or C++, but that using the wrong number of spaces might cause subtle incorrect behavior if someone forgets or if someone's editor is set up wrong, and to me, the benefit is pretty questionable.

bitprophet
Jul 22, 2004
Taco Defender
Yea, that Goodger link was it, much thanks (looks like he's updated the layout a little bit since I last saw it though, but in a good way).

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

jupo posted:

http://diveintopython.org/ is usually what's quoted on comp.lang.python when this question comes up. It's really well organized and I picked python up in a day or two after reading it.

Slightly old, but the #python folks on freenode are reluctant to suggest DIP because, while some parts of it might be decent, it explains some things very poorly. Case in point: this page on "private functions". Not to mention that the whole thing was also originally written for python 2.2.

For beginning programmers, Think Python is much nicer.

Bozart
Oct 28, 2006

Give me the finger.
The ibm developerworks site also seems to have a lot of short articles, although they are not well organized as far as I can see.

I gotta say, even though I don't code in Python professionally it has been really informative for the other programming languages that I do use.

ATLbeer
Sep 26, 2004
Über nerd
Retarded question but, I just can't seem to find the right words to Google for.

I have a list that I want to iterate over the list and run the same function against all the items in the list in place.

I know there is a shortcut here but, my brain isn't working properly right now

hey mom its 420
May 12, 2007

Just use a generator.
code:
xs = [2,3,4,5,6,7]
xs_modified = (a*2 for a in xs)
then you can iterate over xs_modified and it will only start doing the computations once you iterate over it.

bitprophet
Jul 22, 2004
Taco Defender
Bonus is correct, but you should know that the general compsci term for this is "mapping", usually in the form of a map() function. The idea being that you "map" some other function onto your list so that the list is modified in place.

Python has map(), but it's considered more Pythonic to use a generator expression (you'll often see list comprehensions which are nearly identical, more common, but actually less preferable) as Bonus showed just above.

Adbot
ADBOT LOVES YOU

Kire
Aug 25, 2006
I'm using IDLE for Python 2.5.2, and when I type help("elif") or something like that, it just says:

drat IDLE posted:

>>> help("from")

Sorry, topic and keyword documentation is not available because the Python
HTML documentation files could not be found. If you have installed them,
please set the environment variable PYTHONDOCS to indicate their location.

On the Microsoft Windows operating system, the files can be built by
running "hh -decompile . PythonNN.chm" in the C:\PythonNN\Doc> directory.

I've googled directions but they don't work...I decompiled the .chm Python25 help file, but I can't get it to display answers within IDLE. I don't want to have to open up the HTML help doc.

  • Locked thread