Is there something similar to list comprehension in dict?

2009-11-20 Thread Peng Yu
I'm wondering if there is something similar to list comprehension for
dict (please see the example code below).


d = dict(one=1, two=2)
print d

def fun(d):#Is there a way similar to list comprehension to change the
argument d so that d is changed?
  d=dict(three=3)

fun(d)
print d

def fun1(d):
  d['one']=-1

fun1(d)
print d


L = [1, 2]
print L

def fun2(L):#this doesn't have any effect on the argument L
  L=[]

fun2(L)
print L#[1, 2]

def fun3(L):# argument L is changed
  L[:]=[1, 2, 3]

fun3(L)
print L#[1, 2, 3]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New syntax for blocks

2009-11-20 Thread Gregory Ewing

Steven D'Aprano wrote:
I don't know what the state of the art on Mac is 
these days, but in 1984s Macs had a standard keyboard layout that let you 
enter most available characters via the keyboard, using sensible 
mnemonics. E.g. on a US keyboard layout, you could get ≠ by holding down 
the Option key and typing =.


They all still seem to work -- presumably generating the
appropriate unicode characters now instead of MacRoman.

I don't think there's any left-arrow character available
on the keyboard though, unfortunately.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: python and web pages

2009-11-20 Thread Diez B. Roggisch

Daniel Dalton schrieb:

Hi,

Here is my situation:
I'm using the command line, as in, I'm not starting gnome or kde (I'm on
linux.)
I have a string of text attached to a variable,. So I need to use one of
the browsers on linux, that run under the command line, eg. lynx,
elinks, links, links2 and do the following.
1. Open a certain web page and find the first text box on the page, and
put this text into the form.
2. Press the submit button, and wait for the result page to load.
3. Click on the 15th link down the page.

So, how do I do this, can anyone point me to some docs or modules that
may help out here?


Use the module "mechanize". It will mimic a browser, and allows you to 
navigate to pages, fill in forms & submit them.


And with lxml or BeatifulSoup, you can extract the link you need to 
press, and then make mechanize visit it.


Diez
--
http://mail.python.org/mailman/listinfo/python-list


Re: convert a string to a regex?

2009-11-20 Thread Diez B. Roggisch

Peng Yu schrieb:

On Wed, Nov 18, 2009 at 9:12 PM, Tim Chase
 wrote:

There are many special characters listed on
http://docs.python.org/library/re.html

I'm wondering if there is a convenient function that can readily
convert a string with the special characters to its corresponding
regex. For example,

"some.thing" => "some\.thing"

Did you try bothering to *read* the page you linked to?

There's a function for escaping strings right there...

Literacy...a worthwhile skill to obtain.


Sorry, I didn't see it. If there are examples besides explanations for
each command, it will help people see the usage of each command more
easily.


Or it will clutter the whole page.

That's not to say the docs can't be improved. But *reading* them will 
always be required.


Diez
--
http://mail.python.org/mailman/listinfo/python-list


Re: hex

2009-11-20 Thread Diez B. Roggisch

hong zhang schrieb:

List,

I want to input hex number instead of int number. in type="int" in following,

parser.add_option("-F", "--forcemcs", dest="force_mcs", type="int", default=0, 
help="index of 11n mcs table. Default: 0.")

How can I do it?


You can't. You can get a string, and convert that with e.g.

 int("FF", 16)

Or you can extend optparse to know a new type, should be possible. That 
would have the advantage that the parser already knows about it & can 
reject faulty input.


Diez

--
http://mail.python.org/mailman/listinfo/python-list


real numbers with infinity precission

2009-11-20 Thread Hans Larsen
I have a READ.me file for real.py, but where could I get that module? I use 
Python 3.+

I hope that sombody can help me

mailto: jo...@mail.dk


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.1 cx_Oracle 5.0.2 "ImportError: DLL load failed: The specified module could not be found."

2009-11-20 Thread Neil Hodgson
André:

> Apparently the error is caused by cx_Oracle not being able to find the
> Oracle client DLLs (oci.dll and others). The client home path and the
> client home path bin directory are in the PATH System Variable and
> oci.dll is there.

   Open the cx_Oracle extension with Dependency Walker
(http://www.dependencywalker.com/) to get a better idea about what the
problem is in more detail.

   Neil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where to find pexpect

2009-11-20 Thread yuzhichang
On 10月13日, 下午9时42分, Jean-Michel Pichavant 
wrote:
> Antoon Pardon wrote:
> > I have been looking forpexpect. The links I find like
> >http://pexpect.sourceforge.netall end up at
> >http://www.noah.org/wiki/Pexpectwhich produces a 404 not
> > found problem.
>
> > Does someone know the current location?
>
> maybe they removed the distribution so you may use "subprocess" :o)
>
> JM

http://pexpect.sourceforge.net seems outdated. I've forked, ported to
Python 3.1, and added more features to pexpect. See 
http://github.com/yuzhichang/pexpect.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is pexpect unmaintained now?

2009-11-20 Thread yuzhichang
On 11月17日, 上午11时40分, yuzhichang  wrote:
> Pexpect2.4 is only available at Pypi. Both the homepage 
> ofpexpect(http://www.noah.org/wiki/Pexpect) and download page
> (http://sourceforge.net/projects/pexpect/files/) are outdated. The
> repository on Github (http://github.com/noahspurrier/pexpect/) has
> been removed.
>
> I ever contacted the author(n...@noah.org) but no response till now.
>
> I'm going to forkpexpecton Github and add some features...

I've forked, ported it to Python 3.1, and added some features. See
http://github.com/yuzhichang/pexpect.

Regards,
Zhichang Yu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SCGIServer and unusal termination

2009-11-20 Thread Eden Kirin

Diez B. Roggisch wrote:


 - save a reference to sys.stdout *before* invoking the server
 - compare to it after interruption. If it has changed, you at least know
that somebody messed with it, and can beat him or whatever you see fit.


Thanks for the help. Finally, I dropped python-scgi module and I wrote 
my own SCGI server. There was not only the problem with stdout, but one 
much serious which made it unusable to me. Every SCGI request was forked 
as a new process, without the ability to access the shared globals 
within the project.


--
www.vikendi.net -/- www.supergrupa.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: TODO and FIXME tags

2009-11-20 Thread Marco Mariani

Jean-Michel Pichavant wrote:

I guess the world is split in two categories, those how come back to fix 
the TODO, and those how don't. I for myself belong to the second, that 
is why I never write TODO comments, I either do the stuff or consider 
this is not important enough to waste time on it. In other words I 
mostly agree with Martin, and envy people belonging to the first category.


I am in a third category, I added this line to my python.vim syntax file

syn keyword pythonTodo  WTF LOL SNAFU contained

and envy those who didn't :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: python gui builders

2009-11-20 Thread sturlamolden
On 18 Nov, 23:56, Kevin Walzer  wrote:

> wxWidgets (the C++ library) has support for a lot of things other than
> UI bits, as well. wxPython itself is mainly a GUI library because the
> additional features of wxWidgets in C++ are redundant in Python.

That is true. Nobody uses wxPython for socket programming in Python.

Qt is also much more than a C++ GUI framework, but in Python it's
mainly (only?) used for GUI.







-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hex

2009-11-20 Thread Peter Otten
hong zhang wrote:

> I want to input hex number instead of int number. in type="int" in
> following,
> 
> parser.add_option("-F", "--forcemcs", dest="force_mcs", type="int",
> default=0, help="index of 11n mcs table. Default: 0.")
> 
> How can I do it?

Workaround for the lazy: '0xff' on the command line instead of 'ff'.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does turtle graphics have the wrong associations?

2009-11-20 Thread Robert Maas, http://tinyurl.com/uh3t
> > Who is your target audience?
> From: "Alf P. Steinbach" 
> Someone intelligent who doesn't know anything or very much about
> programming and wants to learn general programming.

I think of what a computer *does* as data processing, and then
programing is simply telling the computer what data processing to
do. In calculator mode, you just tell the computer one step at a
time and immediately see the result before giving the next command.
In program mode, you tell the computer the whole sequences of steps
before the computer does even the first, which requires planning
the whole sequence in your mind ahead of time. Lisp's REP allows
you to use calculator mode when doing a dry run, then just wrap
PROG around it and viola you have a program of all the steps
together, thus bridging the gap between calculator and program mode
painlessly.

The two "hard" things about programming are syntax and planning.
REP gets rid of the need to plan in your mind before writing the
code, but you're still stuck with the syntax. My proposed no-syntax
IDE *also* gets rid of the need to bother with any
programming-language syntax. I've been proposing it for years, but
nobody has shown any interest, so I'm spending my time on other
things, but sometime in the next several months I am very likely to
go ahead and implement no-syntax IDE as part of
http://TinyURL.Com/NewEco.

> I assume an intelligent reader, someone who doesn't balk at a few
> technical terms here and there.

There's a **major** difference between the ability to figure out
complex puzzles and the ability to memorize jargon. Case in point:
I placed top-five in Putnam math context despite disability whereby
it was very difficult for me to memorize vocabulary/jargon. Then I
flunked out of graduate school because suddenly I was expected to
(but unable to) memorize ten definitions/lemmas to solve each
homework problem.

Ideally, with either somebody like me with memorization disability,
or a very young child who just naturally by age has trouble
learning more than one concept or term simultaneously, you should
introduce only one concept or term at a time, and exerecise the
person's mind with that concept or term for a while before moving
to the next.

> It's like the difference between driving a car and designing one.
> You don't need an engineering degree to drive a car. :-)

Sure some humans can be trained like pigeons to do the motions of
driving a car through a fixed course without having the slightest
concept of what's really happening. But to be able to respond
appropriately to new situations, it really helps to understand that
the brake pedal does *not* stop the car, it merely pulls a lever
that presses a plate against a wheel causing excess friction
causing the wheel to gradualy slow down, which is connected to the
tires causing *them* to resist motion of car against road, which on
non-slippery surfaces and with *gentle* braking results in the car
slowing down, but with **sudden** pressure on brake, or on slick
surfaces, the wheels stop turning completely and simply slide
against the roadway, causing loss of control of both yaw and
momentum, so suddenly your whole car is spinning about a vertical
axis as well as no longer going around the road-curve but instead
veering in a straight line across opposing traffic lanes or over
the edge of the "S curve" of the Bay Bridge and then 200 feet down
to a rather violent meeting with Yerba Buena Island.

I hate that "CHECK ENGINE" light, because there's usually no way
the driver of the vehicle actually *can* check the engine in any
meaningful way to determine why the light is on. I think it really
means "check" in the sense of a cloak-room, where you "check" your
raincoat and umbrella by handing them to a clerk, thus you really
do "check" your automobile by handing it over to a mechanic.

By the way, I don't want Python running on my Macintosh,
   because it might eat my mouse.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: break LABEL vs. exceptions + PROPOSAL

2009-11-20 Thread Lo'oris
On Nov 18, 7:13 pm, Terry Reedy  wrote:
> It amounts to duplicating raise x...exception x as break xcontinue x
> in the name of aesthetics and supposed efficiency. There would be no new
> functionality nor any abbreviation of code. The semantics of

there would be abbreviation: you wouldn't have to declare somewhere a
dummy exception class.

> anyplace'. The OP gives as a reason the possibility of a typo creating a
> raise x ... except y mis-match. But a break x ... continue y mismatch is
> equally likely.

no: if you mismatch a label in this case, it should be treated as a
syntax error, not as an
unhandled exception which you might not notice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: real numbers with infinity precission

2009-11-20 Thread Steven D'Aprano
On Thu, 19 Nov 2009 09:50:44 +0100, Hans Larsen wrote:

> I have a READ.me file for real.py, but where could I get that module? I
> use Python 3.+
> 
> I hope that sombody can help me

Have you googled for "real.py"?


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python gui builders

2009-11-20 Thread Simon Hibbs
On 18 Nov, 22:11, Stef Mientki  wrote:
> Simon Hibbs wrote:
> > On 18 Nov, 07:51, sturlamolden  wrote:
>
> >> GPL
>
> > PyQT is GPL for now, but Qt itself is available under the LGPL as is
> > PySide. Eventualy PySide, which tracks the PyQT API, will supplant it
> > and the issue will be moot. For now it can be a problem, but PyQT
> > developer licenses are very afordable at only a few hundred dollars.
> > If a commercial project can't aford that, it's got problems.
>
> > Only you can know enough to make an informed decision. Wx does look
> > more usable than last time I used it for a project and is a fine
> > option too, for me though QT is the gold standard against all others
> > are measured, and generaly found wanting.
>
> > Simon Hibbs
>
> Wouldn't it be nice
> if each fan of some form of GUI-package,
> would post it's code (and resulting images) for generating one or two
> standard GUI-forms ?
>
> Then everyone can judge the differences,
> and see what's simple and not  so simple !!

I don't think a list like this is a great way to do that. There are
plenty of examples and tutorials available for each option.

Simon Hibbs
-- 
http://mail.python.org/mailman/listinfo/python-list


Input characters not available on the keyboard (was: New syntax for blocks)

2009-11-20 Thread Ben Finney
Gregory Ewing  writes:

> Steven D'Aprano wrote:
> > I don't know what the state of the art on Mac is these days, but in
> > 1984s Macs had a standard keyboard layout that let you enter most
> > available characters via the keyboard, using sensible mnemonics.
> > E.g. on a US keyboard layout, you could get ≠ by holding down the
> > Option key and typing =.
[…]

> I don't think there's any left-arrow character available on the
> keyboard though, unfortunately.

I'm glad to live in an age when free-software “Input Methods” for many
different character entry purposes are available in good operating
systems. I switch between them using SCIM http://www.scim-im.org/>.
At a pinch, when I'm without my GUI, I can turn some of them on with
Emacs. Common input methods → joy.

I usually default to the “rfc1345” input method which has many
non-keyboard characters available via two-character mnemonics from the
eponymous RFC document — which appears to be about the only purpose that
document has any more.

-- 
 \ “The most dangerous man to any government is the man who is |
  `\   able to think things out for himself, without regard to the |
_o__)  prevailing superstitions and taboos.” —Henry L. Mencken |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New syntax for blocks

2009-11-20 Thread Carl Banks
On Nov 19, 12:20 am, Gregory Ewing 
wrote:
> Steven D'Aprano wrote:
> > I don't know what the state of the art on Mac is
> > these days, but in 1984s Macs had a standard keyboard layout that let you
> > enter most available characters via the keyboard, using sensible
> > mnemonics. E.g. on a US keyboard layout, you could get ≠ by holding down
> > the Option key and typing =.
>
> They all still seem to work -- presumably generating the
> appropriate unicode characters now instead of MacRoman.

³It¹s about time.²


Carl Banks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New syntax for blocks

2009-11-20 Thread Ben Finney
Carl Banks  writes:

> On Nov 19, 12:20 am, Gregory Ewing 
> wrote:
> > They all still seem to work -- presumably generating the appropriate
> > unicode characters now instead of MacRoman.
>
> ³It¹s about time.²

I � Unicode.


(lrf, gung *vf* qryvorengr, sbe gur uhzbhe-vzcnverq nzbat lbh)

-- 
 \  “Courteous and efficient self-service.” —café, southern France |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting properly one subprocess output

2009-11-20 Thread Bas
On Nov 18, 12:25 pm, Jean-Michel Pichavant 
wrote:
> Hi python fellows,
>
> I'm currently inspecting my Linux process list, trying to parse it in
> order to get one particular process (and kill it).
> I ran into an annoying issue:
> The stdout display is somehow truncated (maybe a terminal length issue,
> I don't know), breaking my parsing.

Below is the script I use to automatically kill firefox if it is not
behaving, maybe you are looking for something similar.

HTH,
Bas


#!/usr/bin/env python

import commands, os
lines = os.popen('ps ax|grep firefox').readlines()
lines = [line for line in lines if 'grep' not in line]
print lines[0]
pid = int(lines[0][:5])
print 'Found pid: %d' %pid
os.system('kill -9 %d' %pid)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SCGIServer and unusal termination

2009-11-20 Thread Дамјан Георгиевски
> everything works just fine, but one thing bothers me. All prints after
> try-except block are executed twice after the Ctrl+C is pressed!
> 
> test.py:
> #-
> from scgi.scgi_server import SCGIServer
> 
> n = 0
> print "Starting server."
> 
> try:
>  SCGIServer().serve()
> except (KeyboardInterrupt, SystemExit):
>  print "Exception!"
> 
> # print lines are executed twice (?!)
> n += 1
> print "Terminating server, attempt %d." % n
> n += 1
> print "Check n: %d." % n
> #-

SCGIServer().serve() forks, so it seems that there are 2 python 
processes continuing to run after SCGIServer().serve()


-- 
дамјан ((( http://damjan.softver.org.mk/ )))

Spammers scratch here with a diamond to find my address:
|||
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inserting Unicode text with MySQLdb in Python 2.4-2.5?

2009-11-20 Thread Keith Hughitt
Hello,

Thanks for the suggestions and information Diez!

On Nov 18, 9:38 am, "Diez B. Roggisch"  wrote:
>
> You are aware that the coding-declaration only affects unicode-literals (the
> ones like u"i'm unicode")? So the above insert-statement is *not* unicode,
> it's a byte-string in whatever encoding your editor happens to save the
> file in.

Thanks. I didn't know that, but that is helpful.

>
> And that's point two: make sure your editor reads and writes the file in the
> same encoding you specified in the comment in the beginning.

That is taken care of: the files are opened/saved as UTF-8.

>
> Makes sense if the execute tries to encode to unicode first - as you didn't
> give it a unicode-object.
>

In Python 2.6 where I originally developed the code, it wasn't
necessary to explicitly specify the type of
some text: it was basically handled for you. It does make sense
though.

>
>
> > So far I've tried a number of different things, including:
>
> >     1. Using Unicode strings (e.g. u"\u212B")
>
> >     2. Manually specifying the encoding using sys.setdefaultencoding
> > ('utf-8')
>
> >     3. Manually enabling Unicode support in MySQLdb
> > (use_unicode=False, charset = "utf8")
>
> You *disabled* unicode here! Unicode is NOT utf-8!!!

Oops. It was enabled when I ran it, I just copied the above text from
somewhere else and forgot to change it. I am aware that Unicode does
not equal
utf-8, but utf-8 is a Unicode encoding, right?

>
> http://www.joelonsoftware.com/articles/Unicode.html

Thanks!

>
> Try the above, and better yet provide self-contained examples that show the
> behavior.
>
> Diez

Still no luck. I also tried using double-quotes instead of single-
quotes around the relevant strings (as suggested over email by
ThreaderSlash), however, that did
not work for me.

Here is a small example of what I'm trying to do. Notice that if you
run it in Python 2.5-2.6, everything works fine. It is only in Python
2.4 that the
below example doesn't work.

= Begin Example ==

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys

def main():
import MySQLdb, getpass

admin = raw_input("Database admin: ")
pw = getpass.getpass("Password: ")
db = MySQLdb.connect(user=admin, passwd=pw)

cursor = db.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS unicode_test;")

cursor.execute('''
CREATE TABLE `unicode_test`.`test` (
  `id`  SMALLINT unsigned NOT NULL AUTO_INCREMENT,
  `name`VARCHAR(255) NOT NULL,
   PRIMARY KEY (`id`), INDEX (`id`)
) DEFAULT CHARSET=utf8;''')

cursor.execute('''
INSERT INTO `unicode_test`.`test` VALUES
  (NULL, 'Ångström');
''')

# Test 1
print "Just printing: %s" % 'Ångström'

# Test 2
cursor.execute("SELECT name FROM unicode_test.test;")
print "From database: %s" % cursor.fetchone()[0].decode('utf-8')

# Test 3 (Manual)
print 'To verify manually: mysql -u %s -p -e "SELECT name FROM
unicode_test.test"' % admin

if __name__ == '__main__':
sys.exit(main())

= End Example 

Any suggestions?
Thanks!
Keith

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting properly one subprocess output

2009-11-20 Thread Paul Rudin
Jean-Michel Pichavant  writes:

> Hi python fellows,
>
> I'm currently inspecting my Linux process list, trying to parse it in
> order to get one particular process (and kill it).
> I ran into an annoying issue:
> The stdout display is somehow truncated (maybe a terminal length
> issue, I don't know), breaking my parsing.
>
> import subprocess
> commandLine = ['ps', '-eo "%p %U %P %y %t %C %c %a"']
> process = subprocess.Popen(commandLine, stdout=subprocess.PIPE,
> stderr=subprocess.PIPE)
> processList, stderrdata = process.communicate()
>
> Here is a sample of what I get in processList.split('\n'):
>
> ' "25487 1122  4344 ? 7-17:48:32  2.5 firefox-bin
> /usr/lib/iceweasel/firefox-"',
> ' "25492 1122  4892 pts/6  00:08 57.2 ipython
> /usr/bin/python /usr/bin/ip"',
>
>
> As you can see, to complete process command line is truncated.
> Any clue on how to get the full version ?
>

You need to pass -ww to ps, otherwise it tries to guess the width of
your terminal and adjust output line lengths accordingly.

-- 
http://mail.python.org/mailman/listinfo/python-list


Does Python 3.x support Unicode-named attributes?

2009-11-20 Thread John Nagle

Does Python 3.x support Unicode-named attributes?

There are several modules which operate on HTML and try to
hammer HTML/XML into Python object attributes.  I've had
BeautifulSoup and "urllib" blow up at various times when
running on non-English HTML/XML.

Got this error today:

urllib.py:1197: UnicodeWarning: Unicode equal comparison failed to convert both 
arguments to Unicode - interpreting

them as being unequal
  res = map(safe_map.__getitem__, s)

John Nagle


--
http://mail.python.org/mailman/listinfo/python-list


ANN: PyGUI 2.1.1

2009-11-20 Thread Greg Ewing

PyGUI 2.1.1 is available:

  http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

This is an emergency bugfix release to repair some major
breakage in the gtk version. Also corrects some other
problems.


What is PyGUI?
--

PyGUI is a cross-platform GUI toolkit designed to be lightweight
and have a highly Pythonic API.

--
Gregory Ewing
greg.ew...@canterbury.ac.nz
http://www.cosc.canterbury.ac.nz/greg.ewing/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Invitation to connect on LinkedIn

2009-11-20 Thread Aahz
In article ,
Chris Rebert   wrote:
>
>How the heck someone sets their account email to a mailinglist, I'll
>never figure out.

This probably is not Jaime's fault.  LinkedIn has an expletive b0rken
implementation where they randomly pick addresses that have been used in
your account when your primary address bounces.  Still a bit odd that
LinkedIn got that address in the first place, but I'm betting on them
being at fault.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A "terminators' club" for clp

2009-11-20 Thread Aahz
In article ,
Terry Reedy   wrote:
>
>Some usenet newsgroups were/are moderated either by a robot, a person, 
>or a team (as you suggested). But a particular newsgroup has to be set 
>up that way from the beginning. Last I knew, it wan/is? difficult to 
>convert an unmoderated group to moderation.

It has gotten exponentially more difficult over the last decade.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language mavens: Is there a programming with "if then else ENDIF" syntax?

2009-11-20 Thread Aahz
In article ,
Steve Ferg   wrote:
>
>Does anybody know a language with this kind of syntax for
>ifThenElseEndif?

Several templating systems, including Cheetah.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python simply not scaleable enough for google?

2009-11-20 Thread Aahz
In article ,
Robert P. J. Day  wrote:
>
>http://groups.google.com/group/unladen-swallow/browse_thread/thread/4edbc406f544643e?pli=1
>
>  thoughts?

Haven't seen this elsewhere in the thread:

http://dalkescientific.com/writings/diary/archive/2009/11/15/10_tasklets.html
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newsgroup for beginners

2009-11-20 Thread Aahz
In article ,
Grant Edwards   wrote:
>
>You've really got to try pretty hard to create one.  But if you
>want to, here's how to do it:
>
> 1) Start by complaining that your program doesn't work because
>of a bug in Python.
>
>  [...]

Post of the month!
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
-- 
http://mail.python.org/mailman/listinfo/python-list


Relative versus absolute paths on Windows

2009-11-20 Thread Jason R. Coombs
The current implementation of Python (2.6.4, 3.1.1) treats \bar as a
relative path but reports it as an absolute path.

>>> ntpath.isabs('\\bar')
True
>>> ntpath.abspath('\\bar')
'C:\\bar'
>>> os.chdir('d:\\')
>>> ntpath.abspath('\\bar')
'd:\\bar'
>>> os.chdir('server\\share')
>>> ntpath.abspath('\\bar')
'server\\share\\bar'

In other words, paths without a drive letter are reported as absolute,
but treated as relative, except in a few special cases.

>>> ntpath.join('d:\\foo', '\\bar')
'\\bar'

In this case, \bar is treated as absolute, and not relative to d:\foo.

This inconsistency means that to effectively resolve one path relative
to another, one has to resort to explicit drive letter manipulation.
See 
http://stackoverflow.com/questions/1654659/find-a-path-in-windows-relative-to-another
for a case in point.

My understanding is that in Windows, a path is only absolute if it
contains a drive letter or it begins with a double-backslash.

Curiously, the .Net Framework seems to be subject to the same
limitation

# using IronPython 2.6RC2
>>> System.IO.Path.IsPathRooted('\\bar')
True
>>> System.IO.Path.Combine('d:\\foo', '\\bar') # expect d:\bar
'\\bar'

The documentation for Combine raises this issue in the Community
Content (http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx).

Furthermore, the Windows API utility is also consistent with this odd
behavior (http://msdn.microsoft.com/en-us/library/bb773660%28VS.
85%29.aspx).

The discussion here (http://groups.google.com/group/comp.os.ms-
windows.programmer.win32/browse_thread/thread/b2ff7a9d1d7c9b5e)
describes absolute paths consistent with my understanding:

  Absolute paths have these characteristics.
  Length is at least 2 characters, AND
  ( Second character is ":", OR First two characters is "\\" )

And according to WikiPedia (http://en.wikipedia.org/wiki/Path_
%28computing%29), "[an] absolute path is a path that points to the
same location on one file system regardless of the working directory."
By this definition, \bar is a relative path on Windows.

Ultimately, I don't care what the definition is. It seems to me,
however, that Python should have a function that can resolve one path
name relative to another, but due to these limitations, it does not. I
should point out that os.path.relpath is not the solution either as
the first parameter is always treated as relative to the current
directory (more info at http://bugs.python.org/issue7195).

I've built workarounds in 
https://svn.jaraco.com/jaraco/python/jaraco.windows/jaraco/windows/filesystem.py
as join() and resolve_path(). I'm happy to continue using these
workarounds, but I wanted to bring this issue to the attention of the
community for any comments or suggestions or answers to the following
questions.

What is the benefit of treating \path as absolute?
Should Python have built-in support for resolving one path relative to
another (such as is jaraco.windows.filesystem.resolve_path does)?
Given the long established behavior of Python and other platforms for
handling absolute paths in Windows, is there a way forward that
handles these cases more elegantly, or is the best approach to just
mumble something nasty under our breath and work around these issues
on a case-by-case basis?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting properly one subprocess output

2009-11-20 Thread Nobody
On Thu, 19 Nov 2009 06:21:09 -0800, Bas wrote:

> Below is the script I use to automatically kill firefox if it is not
> behaving, maybe you are looking for something similar.

> lines = os.popen('ps ax|grep firefox').readlines()

This isn't robust. It will kill any process with "firefox" anywhere in its
command line, which isn't limited to processes which are actually running
the firefox web browser.

> lines = [line for line in lines if 'grep' not in line]

This line excludes one such process, but there may be others.

A more robust approach would be to check for the string in the command
name (i.e. argv[0]) rather than the complete command-line, by using e.g.
"ps ... -o pid,comm": 

  lines = os.popen('ps axheo pid,comm').readlines()
  lines = [line.strip().split(' ', 1) for line in lines]
  lines = [(int(pid), cmd) for pid, cmd in lines if 'firefox' in cmd]

Better still would be to check that "firefox" is a complete word, not part
of one, e.g. with the regular expression r"\bfirefox\b". This would match
"firefox", "/usr/bin/firefox", "firefox-bin", etc, but not e.g.
"kill_firefox", e.g.:

  lines = [(int(pid), cmd) for pid, cmd in lines if re.search(r'\bfirefox\b', 
cmd)]

That's about as good as you can get without using non-portable mechanisms
such as /proc/*/exe.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SCGIServer and unusal termination

2009-11-20 Thread Eden Kirin

Дамјан Георгиевски wrote:

SCGIServer().serve() forks, so it seems that there are 2 python 
processes continuing to run after SCGIServer().serve()


I noticed that which makes it unusable to me. Also, it took me almost 
whole day to realize this. I'm adopting a huge application to work with 
SCGI which shares a certain amount of data between working threads and 
SCGI handler. I couldn't realize the cause of erratic and unconsistent 
data behaviour. After diving into python-scgi code, I gave it up and 
wrote my own SCGI server.


--
www.vikendi.net -/- www.supergrupa.com
--
http://mail.python.org/mailman/listinfo/python-list


Python/HTML integration: phileas v0.3 released

2009-11-20 Thread papa hippo
The prime goal of 'phileas' is to enable html code to be seamlessly
included in python code in a natural looking syntax, without resorting
to templatng language.

see:

http://larry.myerscough.nl/phileas_project/

I intend to submit phileas to the python.announce  forum within the
next few days. Any feedback received now will be gratefully received
and may lead to improved quality of that submission.


Larry Myerscough
Eindhoven NL
hip...@chello.nl

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/HTML integration: phileas v0.3 released

2009-11-20 Thread Steve Howell
On Nov 19, 10:53 am, papa hippo  wrote:
> The prime goal of 'phileas' is to enable html code to be seamlessly
> included in python code in a natural looking syntax, without resorting
> to templatng language.
>
> see:
>
> http://larry.myerscough.nl/phileas_project/
>
> I intend to submit phileas to the python.announce  forum within the
> next few days. Any feedback received now will be gratefully received
> and may lead to improved quality of that submission.
>

Hi Larry, looks like interesting stuff!

There appears to be a problem with this page:

http://larry.myerscough.nl/show_python_source.py?script_filename=./MyPage.py

IOError: [Errno 2] No such file or directory: './MyPage.py'

I do like the idea of having a more Python-oriented way to generate
HTML.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python 3.x support Unicode-named attributes?

2009-11-20 Thread Martin v. Löwis
> Does Python 3.x support Unicode-named attributes?

Most certainly, yes. All identifiers (and thus all attribute
names) are Unicode strings in Python 3.x.

> There are several modules which operate on HTML and try to
> hammer HTML/XML into Python object attributes.  I've had
> BeautifulSoup and "urllib" blow up at various times when
> running on non-English HTML/XML.
> 
> Got this error today:
> 
> urllib.py:1197: UnicodeWarning: Unicode equal comparison failed to
> convert both arguments to Unicode - interpreting
> them as being unequal
>   res = map(safe_map.__getitem__, s)

Perhaps the library you were using modified __dict__ directly,
thus getting non-string attribute names into the dict? Or perhaps
s is not a Unicode string?

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Is an interactive command a block?

2009-11-20 Thread Alf P. Steinbach

The CPython 3.1.1 language reference §4.1 says

  "Each command typed interactively is a block."

It also says

  "If a name is bound in a block, it is a local variable of that block, unless
   declared as nonlocal"

Even with a non-literal try-for-best-meaning reading I can't get this to mesh 
with the actual behavior of the interpreter, e.g.


  >>> for x in "poi":
  ...fandango = 666
  ...
  >>> fandango
  666
  >>> _

My current understanding is (A) that the interpreter is correct in this respect 
(for one would harldly want the effects of statements to be fundamentally 
different in interpreted mode, except the presentation of expression results), 
and (B), but here I'm less sure, that the documentation is incorrect.


So what I'm asking about is mainly (B), because if the documentation is correct 
after all, then there's something I haven't grokked. :-)



Cheers,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is an interactive command a block?

2009-11-20 Thread Steven D'Aprano
On Thu, 19 Nov 2009 21:37:17 +0100, Alf P. Steinbach wrote:

> The CPython 3.1.1 language reference §4.1 says
> 
>"Each command typed interactively is a block."
> 
> It also says
> 
>"If a name is bound in a block, it is a local variable of that block,
>unless
> declared as nonlocal"
> 
> Even with a non-literal try-for-best-meaning reading I can't get this to
> mesh with the actual behavior of the interpreter, e.g.
> 
>>>> for x in "poi":
>...fandango = 666
>...
>>>> fandango
>666
>>>> _
> 
> My current understanding is (A) that the interpreter is correct in this
> respect (for one would harldly want the effects of statements to be
> fundamentally different in interpreted mode, except the presentation of
> expression results), and (B), but here I'm less sure, that the
> documentation is incorrect.


Why do you say that? I don't see what it is in the command you typed that 
leads you to think the documentation is incorrect.

The first command you type is:

for x in "poi":
fandango = 666


which binds two names, x and fandango. Since you are not typing them in a 
function or class definition, locals() is globals() and the two local 
names you create happen to also be globals.

The next two commands you type:

fandango
_

don't bind anything, so aren't relevant.

If it helps:


>>> for x in "poi":
... fandango = 666
...
>>> locals() is globals()
True
>>> fandango
666
>>> locals()['fandango']
666
>>> import __main__
>>> __main__.fandango
666



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the naming convention for accessor of a 'private' variable?

2009-11-20 Thread Steven D'Aprano
On Wed, 18 Nov 2009 18:47:34 -0800, Chris Rebert wrote:

> On Wed, Nov 18, 2009 at 6:27 PM, Peng Yu  wrote:
>> http://www.python.org/dev/peps/pep-0008/
>>
>> The above webpage states the following naming convention. Such a
>> variable can be an internal variable in a class. I'm wondering what is
>> the naming convention for the method that access such variable.
>>
>>    - _single_leading_underscore: weak "internal use" indicator.  E.g.
>>    "from M
>>      import *" does not import objects whose name starts with an
>>      underscore.
> 
> If there's a method to access the variable, then it's not all that
> private, is it?

True, but it might be read-only, or the accessor might do validation to 
ensure that the caller doesn't stuff a string in something expected to be 
a float, or some sort of computed attribute. That's why we have 
properties.


> Accessor methods are not Pythonic. 

Accessor methods are *usually* not Pythonic, at least not the way they 
are commonly used in Java.

In fact, Python has at least two built-in accessor functions:

globals()
locals()

There may be others.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does turtle graphics have the wrong associations?

2009-11-20 Thread Steven D'Aprano
On Thu, 19 Nov 2009 02:00:58 -0800, Robert Maas, http://tinyurl.com/uh3t
wrote:

> My proposed no-syntax
> IDE *also* gets rid of the need to bother with any programming-language
> syntax. I've been proposing it for years, but nobody has shown any
> interest

I'm interested. No-syntax IDE? How is this even possible?

The only way I can think of is some sort of wizard interface. E.g. 
instead of having to remember the syntax for a slice, you click the 
"Slice" button and the computer prompts you to enter some combination of 
start, end, step, then generates the syntax [a:b:c] for you.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is an interactive command a block?

2009-11-20 Thread Alf P. Steinbach

* Steven D'Aprano:

On Thu, 19 Nov 2009 21:37:17 +0100, Alf P. Steinbach wrote:


The CPython 3.1.1 language reference §4.1 says

   "Each command typed interactively is a block."

It also says

   "If a name is bound in a block, it is a local variable of that block,
   unless
declared as nonlocal"

Even with a non-literal try-for-best-meaning reading I can't get this to
mesh with the actual behavior of the interpreter, e.g.

   >>> for x in "poi":
   ...fandango = 666
   ...
   >>> fandango
   666
   >>> _

My current understanding is (A) that the interpreter is correct in this
respect (for one would harldly want the effects of statements to be
fundamentally different in interpreted mode, except the presentation of
expression results), and (B), but here I'm less sure, that the
documentation is incorrect.



Why do you say that? I don't see what it is in the command you typed that 
leads you to think the documentation is incorrect.


The first command you type is:

for x in "poi":
fandango = 666


which binds two names, x and fandango. Since you are not typing them in a 
function or class definition, locals() is globals() and the two local 
names you create happen to also be globals.


Thanks, that may be it.

In most other languages I'm familiar with, if a name is local then it isn't 
global (and vice versa), and I had that as an underlying assumption since it 
doesn't appear to be mentioned in the documentation.


However, I find a language reference statement that alludes to this: "(The 
variables of the module code block are local and global.)"


Hm...



The next two commands you type:

fandango
_

don't bind anything, so aren't relevant.


Well it showed that 'fandango' had been defined as a global. :-)



If it helps:



for x in "poi":

... fandango = 666
...

locals() is globals()

True

fandango

666

locals()['fandango']

666

import __main__
__main__.fandango

666


Yeah, helps.

I feel that there's still something lacking in my understanding though, like 
how/where the "really actually just pure local not also global" is defined for 
function definition, but it's now just a vague feeling of something missing, not 
a feeling of direct contradiction as I had when I believed local != global.



Cheers, & thanks,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Re: make two tables having same orders in both column and row names

2009-11-20 Thread Jon Clements
On Nov 18, 8:57 pm, Ping-Hsun Hsieh  wrote:
> Hi,
>
> I would like to compare values in two table with same column and row names, 
> but with different orders in column and row names.
> For example, table_A in a file looks like the follows:
> AA100   AA109   AA101   AA103   AA102
> BB1     2       9       2.3     1       28
> BB3     12      9       2.3     1       28
> BB9     0.5     2       2.3     1       28
> BB2     2       9       21      1       20
>
> Table_B in the other file looks like the follows:
> AA101   AA109   AA100   AA103   AA102
> BB1     2       9       2.3     2       28
> BB2     2       9       2.3     1       28
> BB9     2       9       2.3     1       28
> BB3     2       2       2       1       28
>
> Can anyone give an efficient way to make the two tables having same orders in 
> column and row names so I can easily and correctly compare the values in 
> positions?
>
> Thanks,
> PingHsun

Use a dictionary with a tuple of the row 'name' and column 'name' as
the key.

The following was put together in a hurry, so take with a pinch of
salt (and brandy or something :))...

t1data = """AA100   AA109   AA101   AA103   AA102
BB1 2   9   2.3 1   28
BB3 12  9   2.3 1   28
BB9 0.5 2   2.3 1   28
BB2 2   9   21  1   20"""


def create_table(what):
from itertools import imap, islice, izip, cycle, repeat
table = filter(None, imap(str.split, what.split('\n')))
table_dict = {}
for cols in islice(table, 1, None):
for row_name, col_name, col in izip(cycle(table[0]), repeat
(cols[0]), islice(cols, 1, None)):
table_dict[(row_name, col_name)] = col
return table_dict


print create_table(t1data)


hth
Jon.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Vim breaks after Python upgrade

2009-11-20 Thread NickC
On Tue, 17 Nov 2009 13:46:25 -0500, Nick Stinemates wrote:

> At least with Gentoo, there's a command to recompile all of the plugins
> you have installed when upgrading python versions.
> 
> Your issue is probably related to that. I don't think VIM uses hardcoded
> locations for scripts at the core.
> 
> If you have any specific questions about the errors you're receiving,
> feel free to submit to the VIM mailing list or stop by the IRC channel:
> #vim on irc.freenode.org
> 

Ok, thanks.  I'm sorry for calling vim clunky; the choice of words 
probably reflected my disbelief at the time.

FWIW, sed'ing 's:2\.5:2\.6:g' doesn't work.   It does change some strings, 
but not (apparently) the numbers that matter.


-- 
NickC
-- 
http://mail.python.org/mailman/listinfo/python-list


python bijection

2009-11-20 Thread Joshua Bronson
I couldn't find a library providing a bijective map data structure
(allowing for constant-time lookups by value) in the few minutes I
looked, so I took a few more minutes to code one up:
http://bitbucket.org/jab/toys/src/tip/bijection.py

Is this at all worth releasing? Comments and suggestions welcome.

Josh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt4 4.4.4 : a bug with highlightBlock ?

2009-11-20 Thread David Boddie
On Wednesday 18 November 2009 11:47, Snouffy wrote:

> I've been trying to do some syntax highlighting using PyQt4. I ported
> the example given in the documentation of Qt4 to Python. It works fine
> on my computer at work (which has PyQt4 version 4.3.3) but doesn't on
> my home computer (which has version 4.4.4) : it gets stuck in an
> infinite loop.

This is a known issue. There are examples distributed with PyQt that should
have been updated to use a slightly different approach.

> Here is the code :
> 
> class MyHighlighter(QtGui.QSyntaxHighlighter):
> def __init__(self, edit):
> QtGui.QSyntaxHighlighter.__init__(self,edit)
> 
> def highlightBlock(self, text):
> myClassFormat = QtGui.QTextCharFormat()
> myClassFormat.setFontWeight(QtGui.QFont.Bold)
> myClassFormat.setForeground(QtCore.Qt.darkMagenta)
> pattern = "\\b[A-Z_]+\\b"
> 
> expression = QtCore.QRegExp(pattern)
> index = text.indexOf(expression);
> while (index >= 0):
> length = expression.matchedLength()
> self.setFormat(index, length, myClassFormat)
> index = text.indexOf(expression, index + length)

You need to change the indexOf() calls to indexIn() calls on the QRegExp
object:

  index = expression.indexIn(text, index + length)

> What am I missing ? Is this a known bug of version 4.4.4 ?

I think there was a behavioural change at some point that affected regular
expression searching in QStrings.

David
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python bijection

2009-11-20 Thread Steven D'Aprano
On Thu, 19 Nov 2009 15:24:46 -0800, Joshua Bronson wrote:

> I couldn't find a library providing a bijective map data structure
> (allowing for constant-time lookups by value) in the few minutes I
> looked, so I took a few more minutes to code one up:
> http://bitbucket.org/jab/toys/src/tip/bijection.py
> 
> Is this at all worth releasing? 


You just did :)


> Comments and suggestions welcome.

If I want a mapping a <-> b, I generally just create a dict {a:b, b:a}. 
What is the advantages or disadvantages of your code over the simplicity 
of the dict approach?

(That is, sell us on the features of your approach.)



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python gui builders

2009-11-20 Thread David Boddie
On Thursday 19 November 2009 11:50, Simon Hibbs wrote:

> I don't think a list like this is a great way to do that. There are
> plenty of examples and tutorials available for each option.

This site has a selection of tutorials that can be used to compare
API and code styles:

  http://zetcode.com/

David
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python bijection

2009-11-20 Thread Joshua Bronson
On Nov 19, 7:05 pm, Steven D'Aprano  wrote:
> If I want a mapping a <-> b, I generally just create a dict {a:b, b:a}.
> What is the advantages or disadvantages of your code over the simplicity
> of the dict approach?

Well for one, you don't have to manually update the mapping from b ->
a if ever the mapping from a -> b changes. With your method you have
to write something like "d[a] = c; d[c] = a; del d[b]" instead of just
"d[a] = c", "del d[d.pop(a)]" instead of just "del d[a]", etc.

More significantly, your approach doesn't actually model a bijection
since there's no distinction between keys (the domain) and values (the
range). In other words, you lose information about which way is the
forward mapping and which is the inverse mapping. Worse, d.keys() and
d.values() would each give you the combination of your keys and
values, neither of which would be right, and d.items() would also
return twice as many elements as you expect with no way to distinguish
which side of the mapping a given pair comes from.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Whom Must We Worship

2009-11-20 Thread furlan
On Sun, 15 Nov 2009 00:17:43 -0800, Mary wrote:

> Whom Must We Worship



> The Decision is yours!

Thank you, I got that.

I choose Python. Thanks for sharing.

ciao,
f

-- 
aa #2301
"...The word that separates that which is dead from that which is 
livingIn the beginning was the word and that word was...CHOICE"
-- Tom Robbins (SLWW)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python bijection

2009-11-20 Thread Carl Banks
On Nov 19, 3:24 pm, Joshua Bronson  wrote:
> I couldn't find a library providing a bijective map data structure
> (allowing for constant-time lookups by value) in the few minutes I
> looked, so I took a few more minutes to code one 
> up:http://bitbucket.org/jab/toys/src/tip/bijection.py
>
> Is this at all worth releasing? Comments and suggestions welcome.


Apart from the GPL, it seems perfectly fine to release, and looks like
an interesting strategy.  I've wanted one of those once in a while,
never enough to bother looking for one or writing one myself.

But you should absolutely not inherit from dict if you're overriding
all it's methods.  It's useless and wasteful to do that, perhaps
dangerous.  You end up using bytes for a small hash table that's never
used.

Plus Python 3 has a notion of Abstract Base Classes: it will allow
customization of isinstance to advertise that your class implements
MutableMapping, which is the right way to do it.


Carl Banks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python bijection

2009-11-20 Thread Ben Finney
Carl Banks  writes:

> On Nov 19, 3:24 pm, Joshua Bronson  wrote:
> > I couldn't find a library providing a bijective map data structure
> > (allowing for constant-time lookups by value) in the few minutes I
> > looked, so I took a few more minutes to code one
> > up:http://bitbucket.org/jab/toys/src/tip/bijection.py
> >
> > Is this at all worth releasing? Comments and suggestions welcome.
>
> Apart from the GPL, it seems perfectly fine to release, and looks like
> an interesting strategy. I've wanted one of those once in a while,
> never enough to bother looking for one or writing one myself.

I would think GPL is an excellent choice for such a library then, if the
author's intention is to encourage more software to be free software so
that it can incorporate a unique library like this.

-- 
 \  “The fact that I have no remedy for all the sorrows of the |
  `\ world is no reason for my accepting yours. It simply supports |
_o__)  the strong probability that yours is a fake.” —Henry L. Mencken |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python bijection

2009-11-20 Thread Joshua Bronson
On Nov 19, 9:17 pm, Carl Banks  wrote:
> Apart from the GPL

what Ben said :)

> it seems perfectly fine to release, and looks like
> an interesting strategy.  I've wanted one of those once in a while,
> never enough to bother looking for one or writing one myself.

glad to hear it! i'll release it to pypi if such feedback continues.

> But you should absolutely not inherit from dict if you're overriding
> all it's methods.  It's useless and wasteful to do that, perhaps
> dangerous.  You end up using bytes for a small hash table that's never
> used.
>
> Plus Python 3 has a notion of Abstract Base Classes: it will allow
> customization of isinstance to advertise that your class implements
> MutableMapping, which is the right way to do it.

Actually that's what I was originally thinking of doing but didn't go
through with it in my first pass out of concern that users might want
isinstance(bijection(), dict) to be True. Now that you bring it up, I
agree that it's the correct way to do it, and have reimplemented
bijection as a MutableMapping (ABCs are actually in Python 2.6). Take
a peek at the new and improved 
http://bitbucket.org/jab/toys/src/tip/bijection.py
if you get a chance and let me know how it looks!

Anyone have any other feedback? For instance, is offering the __call__
syntax for the inverse mapping wonderful or terrible, or maybe both?

Thanks,
Josh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FYI: ConfigParser, ordered options, PEP 372 and OrderedDict + big thank you

2009-11-20 Thread Scott David Daniels

Jonathan Fine wrote:...

A big thanks to Armin Ronacher and Raymond Hettinger for
   PEP 372: Adding an ordered dictionary to collections
...  I prototyped (in about an hour).

I then thought - maybe someone has been down this path before

So all that I want has been done already, and will be waiting for me 
when I move to Python3.


So a big thank you is in order.


And thank you for, having done that, not simply smiling because your
work was lighter.  Instead you described a great work path and handed
an attaboy to a pair of people that richly deserve attaboys.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Inserting Unicode text with MySQLdb in Python 2.4-2.5?

2009-11-20 Thread John Nagle

Keith Hughitt wrote:

Hi all,

I ran into a problem recently when trying to add support for earlier
versions of Python (2.4 and 2.5) to some database related code which
uses MySQLdb, and was wondering if anyone has any suggestions.

With later versions of Python (2.6), inserting Unicode is very simple,
e.g.:

# -*- coding: utf-8 -*-
...
cursor.execute('''INSERT INTO `table` VALUES (0,
'Ångström'),...''')

When the same code is run on earlier versions, however, the results is
either garbled text (e.g. "Ã or "?" instead of "Å" in Python 2.5), or
an exception being thrown (Python 2.4):

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in
position 60: ordinal not in range(128)

So far I've tried a number of different things, including:

1. Using Unicode strings (e.g. u"\u212B")

2. Manually specifying the encoding using sys.setdefaultencoding
('utf-8')

3. Manually enabling Unicode support in MySQLdb
(use_unicode=False, charset = "utf8")


   No, that's backwards.  Try:

db = MySQLdb.connect(host="localhost",
use_unicode = True, charset = "utf8",
user=username, passwd=password, db=database)

"use_unicode" means that you want MySQLdb to accept and return
Unicode strings.  "charset="utf8" means you want MySQLdb to
negotiate with the server to use UTF8 on the socket connecting
it to the database.  This works fine in Python 2.4 and 2.5.
Returned strings will be in Unicode.

At the database end, you have to make sure that 1) MySQL was
built with Unicode support (it usually is), 2) the database
fields of interest are in Unicode.  I suggest

ALTER DATABASE dbname DEFAULT CHARACTER SET utf8;

before doing any CREATE TABLE operations. Then strings
will be UTF8 in the database.

Read this: http://dev.mysql.com/doc/refman/5.0/en/charset-unicode.html

It all works quite well.

John Nagle
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a Carriage Return in Unicode

2009-11-20 Thread Scott David Daniels

MRAB wrote:

u'\u240D' isn't a carriage return (that's u'\r') but a symbol (a visible
"CR" graphic) for carriage return. Windows programs normally expect
lines to end with '\r\n'; just use u'\n' in programs and open the text
files in text mode ('r' or 'w').



This is the one thing from standards that I believe Microsoft got right
where others did not.  The ASCII (American Standard for Information
Interchange) standard end of line is _both_ carriage return (\r) _and_
line feed (\n) -- I believe in that order.

The Unix operating system, in its enthusiasm to make _everything_
simpler (against Einstein's advice, "Everything should be made as simple
as possible, but not simpler.") decided that end-of-line should be a
simple line feed and not carriage return line feed.  Before they made
that decision, there was debate about the order of cr-lf or lf-cr, or
inventing a new EOL character ('\037' == '\x1F' was the candidate).

If you've actually typed on a physical typewriter, you know that moving
the carriage back is a distinct operation from rolling the platen
forward; both operations are accomplished when you push the carriage
back using the bar, but you know they are distinct.  Hell, MIT even had
"line starve" character that moved the cursor up (or rolled the platen
back).


Lots of people talk about "dos-mode files" and "windows files" as if
Microsoft got it wrong; it did not -- Unix made up a convenient fiction
and people went along with it. (And, yes, if Unix had been there first,
their convention was, in fact, better).

So, sorry for venting, but I have bee wanting to say this in public
for years.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Urwid 0.9.9 - Console UI Library

2009-11-20 Thread Tim Roberts
"Michel Claveau - MVP" wrote:
>
>Hi! 
>
>You forget to write "urwid" do not run under Windows.

He also forgot to write "urwid" do not run under CP/M or OS/360.  Why did
you feel compelled to post this three times?  If it supported Windows, it
would say so.  The fact that it doesn't say so means it isn't supported.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DOM related question and problem

2009-11-20 Thread Stefan Behnel
elca, 18.11.2009 19:04:
> these day im making python script related with DOM.
> 
> problem is these day many website structure is very complicate .
> [...]
> what is best method to check  can extract such like following info quickly?

This should help:

http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/HTML integration: phileas v0.3 released

2009-11-20 Thread Stefan Behnel
papa hippo, 19.11.2009 19:53:
> The prime goal of 'phileas' is to enable html code to be seamlessly
> included in python code in a natural looking syntax, without resorting
> to templatng language.

I assume you know XIST, ElementTree's ElementMaker, and all those other
ways of generating XML/HTML from Python code in a natural looking way?

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Michele Simionato
On Nov 20, 4:18 am, Peng Yu  wrote:
> I'm wondering if there is something similar to list comprehension for
> dict

Yes, but only in Python 3:

>>> {(i, x) for i, x in enumerate('abc')}
{(0, 'a'), (1, 'b'), (2, 'c')}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Stefan Behnel
Peng Yu, 20.11.2009 04:18:
> I'm wondering if there is something similar to list comprehension for
> dict (please see the example code below).

A list comprehension is an expression that produces a list, e.g.

[ i**2 for i in range(10) ]

Your example below uses a slice assignment.


> def fun(d):#Is there a way similar to list comprehension to change the
> argument d so that d is changed?
>   d=dict(three=3)
> [...]
> def fun3(L):# argument L is changed
>   L[:]=[1, 2, 3]

You can use  d.update(...)

It accepts both another dict as well as a generator expression that
produces item tuples, e.g.

d.update( (i, i**2) for i in range(10) )

Does that help?

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Stefan Behnel
Stefan Behnel, 20.11.2009 09:24:
> You can use  d.update(...)
> 
> It accepts both another dict as well as a generator expression that
> produces item tuples, e.g.
> 
> d.update( (i, i**2) for i in range(10) )

This also works, BTW:

>>> d = {}
>>> d.update(value=5)
>>> d
{'value': 5}

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: non-copy slices

2009-11-20 Thread Ajit Kumar
On Thu, Nov 19, 2009 at 8:14 PM, Ethan Furman  wrote:
>> No I'm well aware that there is no deep copy of the objects and the lists
>> only keep references to the objects and in essence they have the same
>> objects in there. But this doesn't mean they are the same list.
>> Modifications to slices are not written back to the original list.
>>
>> x = range(5)
>> y = x[1:3]
>> y[0] = 13
>> x[1] == y[0]  --> False
>>
>> Of course if I modify the object in the slice then the original list will
>> see the change, but this is not what I was saying. Second and more
>> importantly it's the performance penalty from allocating a large number of
>> lists produced from the slices and the copy of the references. islice does
>> not have this penalty, it should only instantiate a small object that
>> iterates on the original list.
>>
>> Themis
>
> So "shallow copy" == "new label created for existing object".
>
> So is your desired behavior to write back to the original list if your
> sub-list is modified?  In other words, you are creating a window onto an
> existing list?  If not, what would happen when a sublist element was
> modified (or deleted, or appended, or ...)?

On a related note, GO encourages use of slices.

http://golang.org/doc/effective_go.html#slices
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Patrick Sabin

Peng Yu wrote:

I'm wondering if there is something similar to list comprehension for
dict (please see the example code below).


Do you mean something like this:

>>> {i:i+1 for i in [1,2,3,4]}
{1: 2, 2: 3, 3: 4, 4: 5}

This works in python3, but not in python2

- Patrick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Paul Rudin
Patrick Sabin  writes:

> Peng Yu wrote:
>> I'm wondering if there is something similar to list comprehension for
>> dict (please see the example code below).
>
> Do you mean something like this:
>
 {i:i+1 for i in [1,2,3,4]}
> {1: 2, 2: 3, 3: 4, 4: 5}
>
> This works in python3, but not in python2

Of course in python 2 you can do:

>>> dict((i, i+1) for i in [1,2,3,4])
{1: 2, 2: 3, 3: 4, 4: 5}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Terry Reedy

Peng Yu wrote:

I'm wondering if there is something similar to list comprehension for
dict (please see the example code below).


Python 3 has list, set, and dict comprehensions.
Don't know about 2.6/7

--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Andre Engels
On Fri, Nov 20, 2009 at 4:18 AM, Peng Yu  wrote:
> I'm wondering if there is something similar to list comprehension for
> dict (please see the example code below).
>
>
> d = dict(one=1, two=2)
> print d
>
> def fun(d):#Is there a way similar to list comprehension to change the
> argument d so that d is changed?
>  d=dict(three=3)
>
> fun(d)
> print d
>
> def fun1(d):
>  d['one']=-1
>
> fun1(d)
> print d
>
>
> L = [1, 2]
> print L
>
> def fun2(L):#this doesn't have any effect on the argument L
>  L=[]
>
> fun2(L)
> print L#[1, 2]
>
> def fun3(L):# argument L is changed
>  L[:]=[1, 2, 3]
>
> fun3(L)
> print L#[1, 2, 3]
> --
> http://mail.python.org/mailman/listinfo/python-list
>

def fun(d):
   d.clear()
   d[three] = 3




-- 
André Engels, andreeng...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


checking 'type' programmatically

2009-11-20 Thread mk


Disclaimer: this is for exploring and debugging only. Really.

I can check type or __class__ in the interactive interpreter:

Python 2.6.2 (r262:71600, Jun 16 2009, 16:49:04)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> 
p=subprocess.Popen(['/bin/ls'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)

>>> p

>>> (so, se) = p.communicate()
>>> so
'abc.txt\nbak\nbox\nbuild\ndead.letter\nDesktop\nhrs\nmbox\nmmultbench\nmmultbench.c\npyinstaller\nscreenlog.0\nshutdown\ntaddm_import.log\nv2\nvm\nworkspace\n'
>>> se
''
>>> so.__class__

>>> type(so)

>>> type(se)


But when I do smth like this in code that is ran non-interactively (as 
normal program):


req.write('stderr type %s' % type(se))
req.write('stderr class %s' % str(se.__class__))

then I get empty output. WTF?

How do I get the type or __class__ into some object that I can display?


Why do that: e.g. if documentation is incomplete, e.g. documentation on 
Popen.communicate() says "communicate() returns a tuple (stdoutdata, 
stderrdata)" but doesn't say what is the class of stdoutdata and 
stderrdata (a file object to read? a string?).


Regards,
mk



--
http://mail.python.org/mailman/listinfo/python-list


Re: python simply not scaleable enough for google?

2009-11-20 Thread Robin Becker

Aahz wrote:

In article ,
Robert P. J. Day  wrote:

http://groups.google.com/group/unladen-swallow/browse_thread/thread/4edbc406f544643e?pli=1

 thoughts?


Haven't seen this elsewhere in the thread:

http://dalkescientific.com/writings/diary/archive/2009/11/15/10_tasklets.html



I looked at this and it looks very good in that stackless appears twice as fast 
as go(lang) (I used to be in the department of computing at Imperial so I 
suppose I have to side with McCabe).


Anyhow, my reading of why Pike was so proud of his set up and tear down of the 
tasks example was that these were real threads.


Presumably that means they could potentially run in parallel on the 10 cpu 
machines of the future.


I'm not so clear on whether the threadless tasklets will run on separate cpus.
--
Robin Becker

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python/HTML integration: phileas v0.3 released

2009-11-20 Thread Daniel Fetchinson
>> The prime goal of 'phileas' is to enable html code to be seamlessly
>> included in python code in a natural looking syntax, without resorting
>> to templatng language.
>>
>> see:
>>
>> http://larry.myerscough.nl/phileas_project/
>>
>> I intend to submit phileas to the python.announce  forum within the
>> next few days. Any feedback received now will be gratefully received
>> and may lead to improved quality of that submission.
>>
>
> Hi Larry, looks like interesting stuff!
>
> There appears to be a problem with this page:
>
> http://larry.myerscough.nl/show_python_source.py?script_filename=./MyPage.py
>
> IOError: [Errno 2] No such file or directory: './MyPage.py'
>
> I do like the idea of having a more Python-oriented way to generate
> HTML.

Have you guys considered markup.py from http://markup.sourceforge.net/
? It's comparable to your project as far as I can see, a more detailed
comparison would probably be useful.

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Tim Golden

Michele Simionato wrote:

On Nov 20, 4:18 am, Peng Yu  wrote:

I'm wondering if there is something similar to list comprehension for
dict


Yes, but only in Python 3:


{(i, x) for i, x in enumerate('abc')}

{(0, 'a'), (1, 'b'), (2, 'c')}


Although the 2.x syntax is hardly onerous:

dict ((i+5, x) for i, x in enumerate ('abc'))


-- obviously without something like the i+5, the example
equates to dict (enumerate ('abc')) 


:)

TJG
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Dave Angel

Peng Yu wrote:

I'm wondering if there is something similar to list comprehension for
dict (please see the example code below).


d = dict(one=1, two=2)
print d

def fun(d):#Is there a way similar to list comprehension to change the
argument d so that d is changed?
  d=dict(three=3)

fun(d)
print d

def fun1(d):
  d['one']=-1

fun1(d)
print d


L = [1, 2]
print L

def fun2(L):#this doesn't have any effect on the argument L
  L=[]

fun2(L)
print L#[1, 2]

def fun3(L):# argument L is changed
  L[:]=[1, 2, 3]

fun3(L)
print L#[1, 2, 3]

  
You confused me by calling it a list comprehension.  All you're using in 
fun3() is a slice.  Using a slice, you can give a new set of values to 
an existing list.


For a dictionary, it's just a bit trickier.  You need two steps in the 
most general case.


def fun4(d):
  d.clear()  #clear out existing entries
   d.update(new_dict)  #copy in new key:val pairs from a 
different dictionary


This function will modify the caller's dictionary, completely replacing 
the contents.


DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Simon Brunning
2009/11/20 Michele Simionato :
> Yes, but only in Python 3:
>
 {(i, x) for i, x in enumerate('abc')}
> {(0, 'a'), (1, 'b'), (2, 'c')}

In Python 2.x, you can do:

>>> dict((i, x) for i, x in enumerate('abc'))
{0: 'a', 1: 'b', 2: 'c'}

(Works in 2.5 - I can't remember when generator expressions were introduced.)

-- 
Cheers,
Simon B.
-- 
http://mail.python.org/mailman/listinfo/python-list


Regexp and multiple groups (with repeats)

2009-11-20 Thread mk

Hello,

>>> r=re.compile(r'(?:[a-zA-Z]:)([\\/]\w+)+')

>>> r.search(r'c:/tmp/spam/eggs').groups()
('/eggs',)

Obviously, I would like to capture all groups:
('/tmp', '/spam', '/eggs')

But it seems that re captures only the last group. Is there any way to 
capture all groups with repeat following it, i.e. (...)+ or (...)* ?


Even better would be:

('tmp', 'spam', 'eggs')

Yes, I know about re.split:

>>> re.split( r'(?:\w:)?[/\\]', r'c:/tmp/spam\\eggs/' )
['', 'tmp', 'spam', '', 'eggs', '']

My interest is more general in this case: how to capture many groups 
with a repeat?


Regards,
mk


--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Will Not Send Email!!

2009-11-20 Thread Victor Subervi
On Thu, Nov 19, 2009 at 5:01 PM, Kev Dwyer  wrote:

> On Thu, 19 Nov 2009 11:28:37 -0400, Victor Subervi wrote:
>
> Hello Victor,
>
> There are some pages on the internet that suggest that this problem my be
> caused by a module named email.py (or email.pyc) in your pythonpath.  If
> you try import smtplib in the interpreter do you get this error message?
> If so, start a new interpreter session and try import email - is the
> email module imported from the stdlib?
>

Both of these import just fine.

>
> If these steps don't help, it might be useful if you can tell us which
> Linux distribution you are using.
>

Python 2.4.3
[r...@13gems ~]# uname -a
Linux 13gems.com.13gems.com 2.6.18-028stab064.8 #1 SMP Fri Nov 6 11:28:25
MSK 2009 x86_64 x86_64 x86_64 GNU/Linux
CentOS 5.4 final
TIA,
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is an interactive command a block?

2009-11-20 Thread Benjamin Kaplan
On Thu, Nov 19, 2009 at 4:42 PM, Alf P. Steinbach  wrote:
> * Steven D'Aprano:
>>
>> On Thu, 19 Nov 2009 21:37:17 +0100, Alf P. Steinbach wrote:
>>
>>> The CPython 3.1.1 language reference §4.1 says
>>>
>>>   "Each command typed interactively is a block."
>>>
>>> It also says
>>>
>>>   "If a name is bound in a block, it is a local variable of that block,
>>>   unless
>>>    declared as nonlocal"
>>>
>>> Even with a non-literal try-for-best-meaning reading I can't get this to
>>> mesh with the actual behavior of the interpreter, e.g.
>>>
>>>   >>> for x in "poi":
>>>   ...    fandango = 666
>>>   ...
>>>   >>> fandango
>>>   666
>>>   >>> _
>>>
>>> My current understanding is (A) that the interpreter is correct in this
>>> respect (for one would harldly want the effects of statements to be
>>> fundamentally different in interpreted mode, except the presentation of
>>> expression results), and (B), but here I'm less sure, that the
>>> documentation is incorrect.
>>
>>
>> Why do you say that? I don't see what it is in the command you typed that
>> leads you to think the documentation is incorrect.
>>
>> The first command you type is:
>>
>> for x in "poi":
>>    fandango = 666
>>
>>
>> which binds two names, x and fandango. Since you are not typing them in a
>> function or class definition, locals() is globals() and the two local names
>> you create happen to also be globals.
>
> Thanks, that may be it.
>
> In most other languages I'm familiar with, if a name is local then it isn't
> global (and vice versa), and I had that as an underlying assumption since it
> doesn't appear to be mentioned in the documentation.
>
> However, I find a language reference statement that alludes to this: "(The
> variables of the module code block are local and global.)"
>
> Hm...
>
>
>> The next two commands you type:
>>
>> fandango
>> _
>>
>> don't bind anything, so aren't relevant.
>
> Well it showed that 'fandango' had been defined as a global. :-)
>
>
>> If it helps:
>>
>>
> for x in "poi":
>>
>> ...     fandango = 666
>> ...
>
> locals() is globals()
>>
>> True
>
> fandango
>>
>> 666
>
> locals()['fandango']
>>
>> 666
>
> import __main__
> __main__.fandango
>>
>> 666
>
> Yeah, helps.
>
> I feel that there's still something lacking in my understanding though, like
> how/where the "really actually just pure local not also global" is defined
> for function definition, but it's now just a vague feeling of something
> missing, not a feeling of direct contradiction as I had when I believed
> local != global.
>

It's because the only blocks in python that have their own scope are
classes and functions. For loops don't have their own scope- they use
the enclosing one, which in this case is globals.

>
> Cheers, & thanks,
>
> - Alf
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Book: Programming Python 3 (Second Edition) now available

2009-11-20 Thread Mark Summerfield
Hi,

I'm delighted to announce that a new edition of my Python 3 book is
now available in the U.S.

"Programming in Python 3 (Second Edition):
A Complete Introduction to the Python Language"
ISBN 0321680561
http://www.qtrac.eu/py3book.html

The book has been fully revised and updated and now covers both Python
3.0
and 3.1, and with the language moratorium (PEP 3003), this second
edition
should be useful for many years to come. And in addition to the
thorough
updating, the book has been extended with new chapters on debugging,
testing, and profiling, and on parsing (including coverage of the
PyParsing and
PLY modules), as well as a new section on coroutines in the advanced
chapter.

The book is aimed at a wide audience, but assumes some programming
experience (not necessarily Python, not necessarily object-oriented).
It teaches solid procedural style programming, then builds on that to
teach solid object-oriented programming, and then goes on to more
advanced
topics (e.g., including a nice way to create validated attributes by
combining class decorators with descriptors). But even newcomers to
Python 3 should be able to write useful (although small and basic)
programs after reading chapter 1, and then go on to create larger and
more sophisticated programs as they work through the chapters.

All the examples are available for download from the book's web site.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does turtle graphics have the wrong associations?

2009-11-20 Thread Robert Maas, http://tinyurl.com/uh3t
> > My proposed no-syntax
> > IDE *also* gets rid of the need to bother with any programming-language
> > syntax. I've been proposing it for years, but nobody has shown any
> > interest
> From: Steven D'Aprano 
> I'm interested. No-syntax IDE? How is this even possible?

I guess you missed what I previously posted. The basic idea is that
you start with test data, and you use menus to select appropriate
data-processing actions to perform on that data. For example, you
manually key in a file name containing test data, or copy and paste
that same file name. Then you select "open file by that name" or
"load all lines from file by that name" etc. from a menu. If you
just opened the file, you now have a stream of input, and you can
select to read one line or one s-expression or one character etc.
from that file. After loading the whole file or one unit of data,
you now have some *real* data to work from. For example, with a
line of input, you might break it into words.

Caveat: When I said "no syntax", I mean no programming syntax, no
syntax to indicate function calls or variable assignment etc. You
still must deal with visual representation of strings and integers
and other essential data objects, which in a way may be considered
to be syntax. But if you want, you can avoid *all* syntax, even for
data, by drawing a *picture* of the individual bits. For some
low-level machine-language training, or boolean algebra lessons,
this might actually be preferable to Arabic numerals and English
letters to represent data values. Seeing a *picture* of something
that looks like a paper tape seems more binary-friendly than seeing
arabic digits "0" and "1" in rows across a page, when studying
operations upon boolean values or bitmasks.

Now if you don't like the burden of navigating the multi-level
menus, a search engine can be available, whereby you key in
keywords for the name of some data-processing operation you either
saw before or a name you can construct in your mind based on naming
conventions.

The extreme case of search engine would be if English-language
pseudo-code can be automatically converted into a very short menu
of most likely data-processing operations. I actually am seriously
considering doing NewEco software development by this means.
Basically I contract people to brainstorm with me in a Delphi
fashion to create the toplevel design of a new computer algorithm,
then we do top-down break into pieces, and continue top-down
break-down as far as it takes until the search engine recognizes
some step as something it already knows how to do.

> The only way I can think of is some sort of wizard interface.
> E.g. instead of having to remember the syntax for a slice, you
> click the "Slice" button and the computer prompts you to enter
> some combination of start, end, step, then generates the syntax
> [a:b:c] for you.

Yeah, it'll be vaguely like that in some ways. For major data,
we'll have the data first, all parameters to the next function to
apply, and *then* we select what function to call on those
parameters. But for minor parameters, we might allow you to choose
the function before filling in the minor-parameter slots. For
example, to select the nth character of string, we might have both
the string and the integer N before we select the NTH function, but
if N is a constant we might instead have just the string and select
the NTH function and fill in the constant N. With the pseudo-code
translation, some of the constant parameters might be apparent in
the English. For example, we have a string, and we say "select the
second word" (actually that's almost HyperTalk, the scripting
language of HyperCard on Macintosh computers), at which point the
constant parameter 2 would be supplied from the word "second" in
the English.
-- 
http://mail.python.org/mailman/listinfo/python-list


Announcement: depikt - the minimalistic python gate to gtk

2009-11-20 Thread DreiJane
Hi all,

these days i make depikt, a python C-extension for building apps with
gtk. It was a challenge for me and big fun. From its short description
on sourceforge.net:

"Python-3 wrappers for GTK. A minimalistic approach - just suited for
GUI-building of apps, in no way for widget-building. Currently 1250
lines for 15 widgets with about 100 methods ... "

depikt is advanced enough now to begin the transition of an 8MB python
app of me to it - simultaneously with the transition to Python-3 and
English. During this process depikt will grow to support for perhaps
25 widgets and 200 methods. From gobject it has connect(),
connect_after(), handler_block(), handler_unblock() and
handler_is_connected(). Still its status is marked as PreAlpha and
depikt not entered to the Python wiki, because
gtk_container_set_focus_chain() is defunct now - a vital method for
fine usable applications. It's difficult to find out why - as it is
the code was working for some time. depikt is very minimalistic:

No python attributes of its classes, let alone properties

No __repr__, no standard __init__

No support for set_property, get_property

No real class hierarchy, there is one abstract base class Pikt, from
which all concrete widgets are inheriting directly

No exposing of Glib to python (but all i need from pango, cairo and
gdk)

Thus the code is very petty, well understandable and easy to extend to
support for other widgets. That was the primary design goal, together
with exact control of encoding issues, support for Python-3 and
registry- and autoconf-free installation. Exception handling is about
average now - there no mimimalism is intended, quite the contrary (for
the long run). depikt will get to some mature state in 2010 - with
perhaps about 3.000 lines then. One C-file will always be sufficient.
atk might be added by means of a second file, also support for
gtk.TreeView might get an own file - but both directly inserted by
#include (no .h planned).

Enjoy, Joost
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread DreiJane
NB: I wondered about about dict(one=1, two=2) - why not d = {one:1,
two:2} ? Since you do not write L=list((1, 2)) either. These composed
objects as basic building blocks make Python code so dense and
beautiful, thus using "{}" means embracing the language's concept.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/HTML integration: phileas v0.3 released

2009-11-20 Thread papa hippo
On 19 nov, 20:18, Steve Howell  wrote:
> On Nov 19, 10:53 am, papa hippo  wrote:
>
> > The prime goal of 'phileas' is to enable html code to be seamlessly
> > included in python code in a natural looking syntax, without resorting
> > to templatng language.
>
> > see:
>
> >http://larry.myerscough.nl/phileas_project/
>
> > I intend to submit phileas to the python.announce  forum within the
> > next few days. Any feedback received now will be gratefully received
> > and may lead to improved quality of that submission.
>
> Hi Larry, looks like interesting stuff!
>
> There appears to be a problem with this page:
>
> http://larry.myerscough.nl/show_python_source.py?script_filename=./My...
>
> IOError: [Errno 2] No such file or directory: './MyPage.py'
>
Oh dear! my blunder; While syncing (with meld) from my test
environment to the live environment, I missed a file. It seems to be
fixed now.

> I do like the idea of having a more Python-oriented way to generate
> HTML.

That's good to hear.


Larry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/HTML integration: phileas v0.3 released

2009-11-20 Thread papa hippo
On 20 nov, 09:02, Stefan Behnel  wrote:
> papa hippo, 19.11.2009 19:53:
>
> > The prime goal of 'phileas' is to enable html code to be seamlessly
> > included in python code in a natural looking syntax, without resorting
> > to templatng language.
>
> I assume you know XIST, ElementTree's ElementMaker, and all those other
> ways of generating XML/HTML from Python code in a natural looking way?
>
> Stefan

Hi Stefan,

Thanks for your feedback.

Yes,  I am aware that phileas might - on the basis of the short
description on this post - come across like a 're-invented wheel'.
There is, however, one big difference between phileas and all other
other similar packages (XIST, ELementTree, HTMLgen, HyperText,
pyhtmloo etc.) that I inspected:

Phileas uses distinct objects to generate each start and end tag,
whereas all the others use a single function call (in some cases
itself generated by a  function call)  to generate a complete well-
formed element including start-tag and (where required) end-tag. In
theory this is less neat and indeed it means one can write 'bad' HTML
(e.g. missing end of paragraphs) with phileas just as easily as when
writing pure html. In practice, however, I find it at a lot easier to
use.

While using pyhtmloo (my previous favourite HTML generator), I had
found myself using awkward complicated artificial constructions in
order to generate all but the simplest HTML - and spent much time
playing 'hunt the missing bracket'. With phileas, these complexities
seem to just fall away.

Put another way, Phileas generates HTML4.0 - warts and all; it is not
a parser or generator of XML.

I'm considering building in checks/warnings for unclosed elements
etc., probably in the next-but-one pre-release.

Larry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to list comprehension in dict?

2009-11-20 Thread Diez B. Roggisch

DreiJane schrieb:

NB: I wondered about about dict(one=1, two=2) - why not d = {one:1,
two:2} ? Since you do not write L=list((1, 2)) either. These composed


because it's not working.

>>> {one : 1}
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'one' is not defined


Yes, that looks nitpicky, but that is exactly the reason one often 
prefers the dict(...)-variant. Because it uses python keywords, it 
spares you to type quotes around all the keys. Which IMHO is more aesthetic.




objects as basic building blocks make Python code so dense and
beautiful, thus using "{}" means embracing the language's concept.


The collection-literals are a great thing, no doubt. But these 
alternatives are not against any concept.


Diez
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a Carriage Return in Unicode

2009-11-20 Thread sturlamolden
On 19 Nov, 01:14, Doug  wrote:

> Thanks for your help!!

A carriage return in unicode is

   u"\r"

how this is written as bytes is dependent on the encoder.

Don't try to outsmart the UTF-8 codec, it knows how to translate "\r"
to UTF-8.


Sturla Molden
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking 'type' programmatically

2009-11-20 Thread exarkun

On 10:10 am, mrk...@gmail.com wrote:


Disclaimer: this is for exploring and debugging only. Really.

I can check type or __class__ in the interactive interpreter:

Python 2.6.2 (r262:71600, Jun 16 2009, 16:49:04)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> 
p=subprocess.Popen(['/bin/ls'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)

>>> p

>>> (so, se) = p.communicate()
>>> so
'abc.txt\nbak\nbox\nbuild\ndead.letter\nDesktop\nhrs\nmbox\nmmultbench\nmmultbench.c\npyinstaller\nscreenlog.0\nshutdown\ntaddm_import.log\nv2\nvm\nworkspace\n'
>>> se
''
>>> so.__class__

>>> type(so)

>>> type(se)


But when I do smth like this in code that is ran non-interactively (as 
normal program):


req.write('stderr type %s' % type(se))
req.write('stderr class %s' % str(se.__class__))

then I get empty output. WTF?

How do I get the type or __class__ into some object that I can display?


Hooray for HTML.

You asked a browser to render "stderr type ".  This 
isn't valid HTML, so pretty much any behavior goes.  In this case, the 
browser seems to be discarding the entire  - not too 
suprising, as it has some features in common with an html tag.


Try properly quoting your output (perhaps by generating your html with a 
real html generation library).


Jean-Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Will Not Send Email!!

2009-11-20 Thread Kev Dwyer
On Fri, 20 Nov 2009 07:58:55 -0500, Victor Subervi wrote:

> On Thu, Nov 19, 2009 at 5:01 PM, Kev Dwyer 
> wrote:
> 
>> On Thu, 19 Nov 2009 11:28:37 -0400, Victor Subervi wrote:
>>
>> Hello Victor,
>>
>> There are some pages on the internet that suggest that this problem my
>> be caused by a module named email.py (or email.pyc) in your pythonpath.
>>  If you try import smtplib in the interpreter do you get this error
>> message? If so, start a new interpreter session and try import email -
>> is the email module imported from the stdlib?
>>
>>
> Both of these import just fine.
> 
> 
>> If these steps don't help, it might be useful if you can tell us which
>> Linux distribution you are using.
>>
>>
> Python 2.4.3
> [r...@13gems ~]# uname -a
> Linux 13gems.com.13gems.com 2.6.18-028stab064.8 #1 SMP Fri Nov 6
> 11:28:25 MSK 2009 x86_64 x86_64 x86_64 GNU/Linux CentOS 5.4 final
> TIA,
> V
> On Thu, Nov 19, 2009 at 5:01 PM, Kev Dwyer
> < href="mailto:kevin.p.dw...@gmail.com";>kevin.p.dw...@gmail.com>
> wrote: On Thu, 19 Nov 2009
> 11:28:37 -0400, Victor Subervi wrote: 
> Hello Victor,
> 
> There are some pages on the internet that suggest that this problem my
> be caused by a module named email.py (or email.pyc) in your
> pythonpath.  If you try import smtplib in the interpreter do you get
> this error message? If so, start a new interpreter session and try
> import email - is the email module imported from the
> stdlib?Both of these import just
> fine.  
> If these steps don't help, it might be useful if you can tell us
> which Linux distribution you are
> using.Python
> 2.4.3[r...@13gems ~]# uname -aLinux  href="http://13gems.com.13gems.com";>13gems.com.13gems.com
> 2.6.18-028stab064.8 #1 SMP Fri Nov 6 11:28:25 MSK 2009 x86_64 x86_64
> x86_64 GNU/Linux CentOS 5.4
> finalTIA,V

Hello Victor,

I ran your script on a CentOS vm (5.2 server 32bit, not quite the same as 
yours but also running python 2.4.3).  It ran without error.  So I 
suspect that either you have a rogue email module/package on your machine 
or there's something wrong with the python install.

You could try:

import email
email.__version__

My interpreter responds "3.0.1"  If you get a different response that 
suggests a dodgy module somewhere - try email.__file__ and see where it's 
located (my interpreter returns /usr/lib/python2.4/email/__init__.pyc).

If the version number is "3.0.1" on your machine then I would check the 
contents of /usr/lib64/python2.4/email/.  Perhaps the base64MIME module 
is missing.

Cheers,

Kev

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: checking 'type' programmatically

2009-11-20 Thread Billy Earney
Try looking at the function 'isinstance', so for example

if isinstance(obj, str):
print "object is a string.."
elif isinstance(obj, int):
print "object is an integer.." 

-Original Message-
From: python-list-bounces+billy.earney=gmail@python.org
[mailto:python-list-bounces+billy.earney=gmail@python.org] On Behalf Of
mk
Sent: Friday, November 20, 2009 4:10 AM
To: python-list@python.org
Subject: checking 'type' programmatically


Disclaimer: this is for exploring and debugging only. Really.

I can check type or __class__ in the interactive interpreter:

Python 2.6.2 (r262:71600, Jun 16 2009, 16:49:04)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import subprocess
 >>> 
p=subprocess.Popen(['/bin/ls'],stdout=subprocess.PIPE,stderr=subprocess.PIPE
)
 >>> p

 >>> (so, se) = p.communicate()
 >>> so
'abc.txt\nbak\nbox\nbuild\ndead.letter\nDesktop\nhrs\nmbox\nmmultbench\nmmul
tbench.c\npyinstaller\nscreenlog.0\nshutdown\ntaddm_import.log\nv2\nvm\nwork
space\n'
 >>> se
''
 >>> so.__class__

 >>> type(so)

 >>> type(se)


But when I do smth like this in code that is ran non-interactively (as 
normal program):

req.write('stderr type %s' % type(se))
req.write('stderr class %s' % str(se.__class__))

then I get empty output. WTF?

How do I get the type or __class__ into some object that I can display?


Why do that: e.g. if documentation is incomplete, e.g. documentation on 
Popen.communicate() says "communicate() returns a tuple (stdoutdata, 
stderrdata)" but doesn't say what is the class of stdoutdata and 
stderrdata (a file object to read? a string?).

Regards,
mk



-- 
http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Will Not Send Email!!

2009-11-20 Thread Carsten Haese
Victor Subervi wrote:
> On Thu, Nov 19, 2009 at 5:01 PM, Kev Dwyer  > wrote:
> 
> On Thu, 19 Nov 2009 11:28:37 -0400, Victor Subervi wrote:
> 
> Hello Victor,
> 
> There are some pages on the internet that suggest that this problem
> my be
> caused by a module named email.py (or email.pyc) in your pythonpath.  If
> you try import smtplib in the interpreter do you get this error message?
> If so, start a new interpreter session and try import email - is the
> email module imported from the stdlib?
> 
> 
> Both of these import just fine.

Kevin neglected to mention that the new interpreter session must be
started in the same directory as the one you're in when you run your
testMail.py script. Since he didn't mention that, we can't be sure that
that's what you did, so this experiment doesn't prove anything.

Please show us a copy-and-paste of your command line window contents
that result from executing <> and then executing
<> immediately thereafter.

--
Carsten Haese
http://informixdb.sourceforge.net

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is an interactive command a block?

2009-11-20 Thread Alf P. Steinbach

* Benjamin Kaplan:

On Thu, Nov 19, 2009 at 4:42 PM, Alf P. Steinbach  wrote:

* Steven D'Aprano:

I feel that there's still something lacking in my understanding though, like
how/where the "really actually just pure local not also global" is defined
for function definition, but it's now just a vague feeling of something
missing, not a feeling of direct contradiction as I had when I believed
local != global.



It's because the only blocks in python that have their own scope are
classes and functions. For loops don't have their own scope- they use
the enclosing one, which in this case is globals.


Thanks, but hey, contradiction: you mention globals as an "enclosing" scope, 
i.e. that a module can have a scope, while stating that only classes and 
functions have their own scope (so, would a module have it's not own scope?).


I think, having now read up and down and sideways in the docs, that the proper 
term in Python is "namespace", and that "scope" in Python refers to where the 
names in a namespace are directly accessible, with a special case for classes, 
namely that the scope of a class' namespace doesn't penetrate down into function 
definitions, hence problem with comprehensions expressed directly in a class 
definition. I believe that's a so called language "wart"  --  which C++ is full 
of, just now discovering some of Python's :-). It's almost like C++'s "most 
vexing parse", a natural and apparently meaningful source code construct that 
due to the detailed rules turns out to be meaningless. I wish language designers 
could be a little less hooked on low level consistency. Because it makes for 
high level inconsistency, very difficult to explain without zillions of details.


But anyways, it's starting to make more sense, yes.


Cheers,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list


Too Many Values To Unpack

2009-11-20 Thread Victor Subervi
Hi;
At one point Dennis Lee Bieber helped me with the following slightly
modified code:

#!/usr/bin/python

import sys,os
sys.path.append(os.getcwd())
import MySQLdb
from login import login
import re, string

def printTree(aTree, level=0):
  tree = []
  for name in sorted(aTree.keys()):
tree.append("%s%s") % ("\t" * level, name)
printTree(aTree[name], level + 1)

def expand(fetched):
  aDict = {}
  for (name, ) in fetched:
aDict[name] = {}
  return aDict

def getChildren(levelDict, level = 0):
  MAXLEVEL = 7
  if level > MAXLEVEL:
return  #possibly the data has a cycle/loop
  for (nm, dt) in levelDict:
cursor.execute('''select c.name from categories as c
  inner join relationship as r
  on c.ID = r.Child
  inner join categories as p
  on r.Parent = p.ID
  where p.category = %s
  order by c.name''', (nm,))
levelDict[nm] = expand(cursor.fetchall())
# recursive call to do next level
getChildren(levelDict[nm], level + 1)
  # no data return as we are mutating dictionaries in place

def catTree():
  user, passwd, db, host = login()
  database = MySQLdb.connect(host, user, passwd, db)
  cursor = database.cursor()
  cursor.execute('''create table if not exists categories
 (ID int(3) unsigned primary key,
 Category varchar(40),
 Parent varchar(40))''')
  cursor.execute('select Category, Parent from categories;')
  data = cursor.fetchall()
  cursor.execute('select Category from categories order by Parent, ID')
  print data
  Categories = [itm[0] for itm in cursor] #untuple single column
  if len(Categories) > 0:
cursor.execute('select Parent from categories order by Parent, ID')
Parents = [itm[0] for itm in cursor]
MAXLEVEL = 15
cursor.execute('''create table if not exists categories
  (ID integer auto_increment primary key,
  Name varchar(40) not null,
  unique (Name)
  )''')
cursor.execute('''create table if not exists Relationship
  (ID integer auto_increment primary key,
  Parent integer not null,
  foreign key (Parent) references categories (ID),
  Child integer not null,
  foreign key (Child) references categories (ID),
  check (Parent <> Child) );''')
# get top level
print 'ok'
cursor.execute('select category from categories order by category')
theTree = expand(cursor.fetchall())
getChildren(theTree)
connection.commit()
return printTree(theTree)
  else:
return ['There are no categories yet.']

catTree()

This throws the error:

[Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58] Traceback (most
recent call last):
[Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58]   File
"/var/www/html/angrynates.com/cart/createCats.py", line 8, in ?
[Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58] from catTree
import catTree
[Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58]   File
"/var/www/html/angrynates.com/cart/catTree.py", line 77, in ?
[Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58] catTree()
[Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58]   File
"/var/www/html/angrynates.com/cart/catTree.py", line 71, in catTree
[Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58]
getChildren(theTree)
[Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58]   File
"/var/www/html/angrynates.com/cart/catTree.py", line 25, in getChildren
[Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58] for (nm, dt)
in levelDict:
[Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58] ValueError: too
many values to unpack

There is only one category in "categories". Please advise.
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Will Not Send Email!!

2009-11-20 Thread Victor Subervi
On Fri, Nov 20, 2009 at 11:05 AM, Kev Dwyer  wrote:

> I ran your script on a CentOS vm (5.2 server 32bit, not quite the same as
> yours but also running python 2.4.3).  It ran without error.  So I
> suspect that either you have a rogue email module/package on your machine
> or there's something wrong with the python install.
>
> You could try:
>
> import email
> email.__version__
>
> My interpreter responds "3.0.1"  If you get a different response that
> suggests a dodgy module somewhere - try email.__file__ and see where it's
> located (my interpreter returns /usr/lib/python2.4/email/__init__.pyc).
>
> If the version number is "3.0.1" on your machine then I would check the
> contents of /usr/lib64/python2.4/email/.  Perhaps the base64MIME module
> is missing.
>

>>> import email
>>> email.__version__
'3.0.1'
>>>
[r...@13gems cart]# ls /usr/lib64/python2.4/email/
base64MIME.py   Encoders.pyoGenerator.pyc  Iterators.py
MIMEAudio.pyo   MIMEMessage.pyc   MIMEText.py Parser.pyo
base64MIME.pyc  Errors.py   Generator.pyo  Iterators.pyc
MIMEBase.py MIMEMessage.pyo   MIMEText.pycquopriMIME.py
base64MIME.pyo  Errors.pyc  Header.py  Iterators.pyo
MIMEBase.pycMIMEMultipart.py  MIMEText.pyoquopriMIME.pyc
Charset.py  Errors.pyo  Header.pyc Message.py
MIMEBase.pyoMIMEMultipart.pyc _parseaddr.py   quopriMIME.pyo
Charset.pyc FeedParser.py   Header.pyo Message.pyc
MIMEImage.pyMIMEMultipart.pyo _parseaddr.pyc  test
Charset.pyo FeedParser.pyc  __init__.pyMessage.pyo
MIMEImage.pyc   MIMENonMultipart.py   _parseaddr.pyo  Utils.py
Encoders.py FeedParser.pyo  __init__.pyc   MIMEAudio.py
MIMEImage.pyo   MIMENonMultipart.pyc  Parser.py   Utils.pyc
Encoders.pycGenerator.py__init__.pyo   MIMEAudio.pyc
MIMEMessage.py  MIMENonMultipart.pyo  Parser.pyc  Utils.pyo

Any other ideas?
TIA,
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regexp and multiple groups (with repeats)

2009-11-20 Thread Neil Cerutti
On 2009-11-20, mk  wrote:
> Hello,
>
> >>> r=re.compile(r'(?:[a-zA-Z]:)([\\/]\w+)+')
>
> >>> r.search(r'c:/tmp/spam/eggs').groups()
> ('/eggs',)
>
> Obviously, I would like to capture all groups:
> ('/tmp', '/spam', '/eggs')

You'll have to do something else, for example:

>>> s = re.compile(r'(?:[a-zA-Z]:)')
>>> n = re.compile(r'[\\/]\w+')
>>> m = s.match('c:/tmp/spam/eggs')
>>> n.findall(m.string[m.end():])
['/tmp', '/spam', '/eggs']

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Will Not Send Email!!

2009-11-20 Thread Victor Subervi
On Fri, Nov 20, 2009 at 11:14 AM, Carsten Haese wrote:

> Kevin neglected to mention that the new interpreter session must be
> started in the same directory as the one you're in when you run your
> testMail.py script. Since he didn't mention that, we can't be sure that
> that's what you did, so this experiment doesn't prove anything.
>
> Please show us a copy-and-paste of your command line window contents
> that result from executing <> and then executing
> <> immediately thereafter.
>

[r...@13gems globalsolutionsgroup.vi]# python testMail.py
Traceback (most recent call last):
  File "testMail.py", line 2, in ?
import smtplib
  File "/usr/lib64/python2.4/smtplib.py", line 49, in ?
from email.base64MIME import encode as encode_base64
ImportError: No module named base64MIME
[r...@13gems globalsolutionsgroup.vi]# python -c "import email; print email"

TIA,
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is an interactive command a block?

2009-11-20 Thread Ethan Furman

Alf P. Steinbach wrote:

* Benjamin Kaplan:

On Thu, Nov 19, 2009 at 4:42 PM, Alf P. Steinbach  wrote:

>>>
I feel that there's still something lacking in my understanding 
though, like
how/where the "really actually just pure local not also global" is 
defined

for function definition, but it's now just a vague feeling of something
missing, not a feeling of direct contradiction as I had when I believed
local != global.



It's because the only blocks in python that have their own scope are
classes and functions. For loops don't have their own scope- they use
the enclosing one, which in this case is globals.



Thanks, but hey, contradiction: you mention globals as an "enclosing" 
scope, i.e. that a module can have a scope, while stating that only 
classes and functions have their own scope (so, would a module have it's 
not own scope?).


module scope == global scope

That is, there is nothing higher than module scope.  (So, yes, global is 
a slight misnomer... in Python it means 'global to a module'.)


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regexp and multiple groups (with repeats)

2009-11-20 Thread Mark Tolonen


"mk"  wrote in message news:he60ha$iv...@ger.gmane.org...

Hello,

>>> r=re.compile(r'(?:[a-zA-Z]:)([\\/]\w+)+')

>>> r.search(r'c:/tmp/spam/eggs').groups()
('/eggs',)

Obviously, I would like to capture all groups:
('/tmp', '/spam', '/eggs')

But it seems that re captures only the last group. Is there any way to 
capture all groups with repeat following it, i.e. (...)+ or (...)* ?


Even better would be:

('tmp', 'spam', 'eggs')

Yes, I know about re.split:

>>> re.split( r'(?:\w:)?[/\\]', r'c:/tmp/spam\\eggs/' )
['', 'tmp', 'spam', '', 'eggs', '']

My interest is more general in this case: how to capture many groups with 
a repeat?


re.findall is what you're looking for.  Here's all words not followed by a 
colon:



import re
re.findall(u'(\w+)(?!:)',r'c:\tmp\spam/eggs')

['tmp', 'spam', 'eggs']

-Mark


--
http://mail.python.org/mailman/listinfo/python-list


Re: python gui builders

2009-11-20 Thread sturlamolden
On 18 Nov, 22:18, David Bolen  wrote:

> With that said, for various reasons I still prefer wxPython to Qt, and
> at the moment, find wxFormBuilder the best fit for my own designs
> (even before the direct Python support, just using XRC).

Personally I prefer wxFormBuilder over QtDesigner for sizer-based
designs.

For quickly creating mock-up designs (GUI or web) there is a Windows
program called "DesignerVista".

-- 
http://mail.python.org/mailman/listinfo/python-list


Split class across multiple files

2009-11-20 Thread eric.frederich
I have a class which holds a connection to a server and a bunch of
services.
In this class I have methods that need to work with that connection
and services.

Right now there are about 50 methods some of which can be quite long.
>From an organizational standpoint, I'd like to have method
implementations in their own files.

Is this possible?  It is recommended?  Should I just stop worrying
about it and have a 5,000 line class?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Too Many Values To Unpack

2009-11-20 Thread Shashank Singh
On Fri, Nov 20, 2009 at 9:15 PM, Victor Subervi wrote:

> Hi;
> At one point Dennis Lee Bieber helped me with the following slightly
> modified code:
>
> #!/usr/bin/python
>
> import sys,os
> sys.path.append(os.getcwd())
> import MySQLdb
> from login import login
> import re, string
>
> def printTree(aTree, level=0):
>   tree = []
>   for name in sorted(aTree.keys()):
> tree.append("%s%s") % ("\t" * level, name)
> printTree(aTree[name], level + 1)
>
> def expand(fetched):
>   aDict = {}
>   for (name, ) in fetched:
> aDict[name] = {}
>   return aDict
>

def getChildren(levelDict, level = 0):
>   MAXLEVEL = 7
>   if level > MAXLEVEL:
> return  #possibly the data has a cycle/loop
>   for (nm, dt) in levelDict:
>

Are you sure your key values are 2-tuples in levelDict?
For-each on dicts enumerates the keys AFAIK

-- 
Regards
Shashank Singh
Senior Undergraduate, Department of Computer Science and Engineering
Indian Institute of Technology Bombay
shashank.sunny.si...@gmail.com
http://www.cse.iitb.ac.in/~shashanksingh
-- 
http://mail.python.org/mailman/listinfo/python-list


Serve Pages Under Different Ownership

2009-11-20 Thread Victor Subervi
Hi;
I'm building a new server after many years hiatus. I currently can only
serve python pages chown'd to root. How do I change this?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


semantics of [:]

2009-11-20 Thread Esmail

Could someone help confirm/clarify the semantics of the [:] operator
in Python?

a = range(51,55)

# 1 ##
b = a[:] # b receives a copy of a, but they are independent


# The following two are equivalent
# 2 ##
c = []
c = a[:] # c receives a copy of a, but they are independent


# 3 ##
d = []
d[:] = a # d receives a copy of a, but they are independent


### 1 ### is the preferred, shorter way to do what ## 2 ## and ## 3 ##
do.

Am I correct with this?

Thanks.

--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >