ANN: Intro+Intermediate Python course, SF, May 10-12

2010-04-01 Thread wesley chun
Need to get up-to-speed with Python as quickly as possible? Come join
me, Wesley Chun, author of Prentice-Hall's bestseller Core Python
Programming, for a comprehensive intro course coming up this May in
beautiful Northern California! Please pass on this note to whomever
you think may be interested. I look forward to meeting you and your
colleagues! feel free to pass around the PDF flyer linked down below.

(Comprehensive) Introduction to Python
Mon-Wed, 2010 May 10-12, 9am-5pm

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(COMPREHENSIVE) INTRO+INTERMEDIATE PYTHON

Although this course may appear to those new to Python, it is also
perfect for those who have tinkered with it and want to fill in the
gaps and/or want to get more in-depth formal training.  It combines
the best of both an introduction to the language as well as a Python
Internals training course.

We will immerse you in the world of Python in only a few days, showing
you more than just its syntax (which you don't really need a book to
learn, right?). Knowing more about how Python works under the covers,
including the relationship between data objects and memory management,
will make you a much more effective Python programmer coming out of
the gate. 3 hands-on labs each day will help hammer the concepts home.

Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware,
NASA, Ubuntu, YouTube, and Red Hat all use Python. Users supporting
or jumping to Plone, Zope, TurboGears, Pylons, Django, Google App
Engine, Jython, IronPython, and Mailman will also benefit!

PREVIEW 1: you will find (and can download) a video clip of a
class session recorded live to get an idea of my lecture style and
the interactive classroom environment at:

http://cyberwebconsulting.com

PREVIEW 2: Partnering with O'Reilly and Pearson, Safari Books
Online has asked me to deliver a 1-hour webcast last Spring called
What is Python?. This was an online seminar based on a session
that I've delivered at numerous conferences in the past. It will give
you an idea of lecture style as well as an overview of the material
covered in the course.

info:http://www.safaribooksonline.com/events/WhatIsPython.html
download (reg req'd):
http://www.safaribooksonline.com/Corporate/DownloadAndResources/webcastInfo.php?page=WhatIsPython
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA

WEB:   http://cyberwebconsulting.com

FLYER: http://starship.python.net/crew/wesc/flyerPP1may10.pdf

LOCALS: easy freeway (101/280/380) with lots of parking plus public
transit (BART and CalTrain) access via the San Bruno stations, easily
accessible from all parts of the Bay Area

VISITORS: free shuttle to/from the airport, free high-speed internet,
free breakfast and regular evening receptions; fully-equipped suites

See website for costs, venue info, and registration. There is a significant
discounts available for full-time students, secondary teachers, and others.

Hope to see you there!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Core Python Programming, Prentice Hall, (c)2007,2001
Python Fundamentals, Prentice Hall, (c)2009
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Google Summer of Code 2010 -- call for participation

2010-04-01 Thread C. Titus Brown
Hello everynoe,

The Python Software Foundation is once again participating in the Google
Summer of Code (GSoC), and we invite student applications from all who wish to
participate.

This year we'll be focusing on the transition to Python 3, so please
bring your porting and extension issues our way!  Any other projects
related to extending Python-the-language and Python libraries are
also welcome.

If you are interested in applying, or in mentoring, please visit Python's
Summer of Code wiki page:

  http://wiki.python.org/moin/SummerOfCode/2010

Please see the GSoC FAQ for general questions about the program:

  http://socghop.appspot.com/document/show/gsoc_program/google/gsoc2010/faqs

thanks,
--titus
-- 
C. Titus Brown, c...@msu.edu
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: sorting ascending/descending with operator.attrgetter

2010-04-01 Thread Steve Holden
Steven D'Aprano wrote:
 On Wed, 31 Mar 2010 22:19:27 -0400, Steve Holden wrote:
 
 I'm the same myself, and I know from personal experience that while I am
 (simply?) seeking accuracy and truth it sometimes bugs the hell out of
 people ...
 
 By the way, why are we acting as if seeking accuracy and truth is a bad 
 thing?
 
We aren't. Or, at least, I'm not trying to convey that. But you have to
remember you aren't conversing with robots here. People have emotions,
and they will affect the way they react to your utterances whether you
like or not, and whether you think it's reasonable or not.

 Personally, if I were interviewing job applicants, one of the things I'd 
 like to know is how well they react to criticism. This especially applies 
 to technical and programming roles. I've managed thin-skinned prima 
 donnas who spit the dummy if someone dares point out they made a mistake, 
 and so long as I'm involved in the hiring process I won't be doing so 
 again. Give me a pedantic, technically precise, obnoxiously *correct* 
 coder over a sloppy one any time.
 
As an employee, possibly (though the expense of stopping his colleagues
from killing him may make the cost prohibitive). As a friend, one might
be prepared to be forgiving.

As a Usenet correspondent I find that too much pedantry becomes tiresome
after a while, and can detract from the pleasures of the correspondence.
It should hardly be necessary to point out that you *aren't*
interviewing job applicants on c.l.py (or at least not overtly).

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: sorting ascending/descending with operator.attrgetter

2010-04-01 Thread Rami Chowdhury
On Wednesday 31 March 2010 22:50:02 Steve Holden wrote:
 When I say 'use soap' 

*use* soap? Sounds awfully Perlish to me, perhaps you meant import soap ;-)?


Rami Chowdhury
Ninety percent of everything is crap. -- Sturgeon's Law
408-597-7068 (US) / 07875-841-046 (UK) / 01819-245544 (BD)
-- 
http://mail.python.org/mailman/listinfo/python-list


jobs in australia jobs in australia for pakistanis jobs in australia melbourne jobs in australia for immigrants jobs in australia for international students jobs in australia for foreigne

2010-04-01 Thread Naeem
jobs in australia jobs in australia for pakistanis jobs in
australia melbourne jobs in australia for immigrants jobs in
australia for international students jobs in australia for
foreigners ON http://jobsinaustralia-net.blogspot.com/  jobs in
australia jobs in australia for pakistanis jobs in australia
melbourne jobs in australia for immigrants jobs in australia for
international students jobs in australia for foreigners ON
http://jobsinaustralia-net.blogspot.com/  jobs in australia jobs in
australia for pakistanis jobs in australia melbourne jobs in
australia for immigrants jobs in australia for international
students jobs in australia for foreigners ON 
http://jobsinaustralia-net.blogspot.com/
jobs in australia jobs in australia for pakistanis jobs in
australia melbourne jobs in australia for immigrants jobs in
australia for international students jobs in australia for
foreigners ON http://jobsinaustralia-net.blogspot.com/  jobs in
australia jobs in australia for pakistanis jobs in australia
melbourne jobs in australia for immigrants jobs in australia for
international students jobs in australia for foreigners ON
http://jobsinaustralia-net.blogspot.com/  jobs in australia jobs in
australia for pakistanis jobs in australia melbourne jobs in
australia for immigrants jobs in australia for international
students jobs in australia for foreigners ON 
http://jobsinaustralia-net.blogspot.com/
jobs in australia jobs in australia for pakistanis jobs in
australia melbourne jobs in australia for immigrants jobs in
australia for international students jobs in australia for
foreigners ON http://jobsinaustralia-net.blogspot.com/  jobs in
australia jobs in australia for pakistanis jobs in australia
melbourne jobs in australia for immigrants jobs in australia for
international students jobs in australia for foreigners ON
http://jobsinaustralia-net.blogspot.com/  jobs in australia jobs in
australia for pakistanis jobs in australia melbourne jobs in
australia for immigrants jobs in australia for international
students jobs in australia for foreigners ON 
http://jobsinaustralia-net.blogspot.com/
jobs in australia jobs in australia for pakistanis jobs in
australia melbourne jobs in australia for immigrants jobs in
australia for international students jobs in australia for
foreigners ON http://jobsinaustralia-net.blogspot.com/  jobs in
australia jobs in australia for pakistanis jobs in australia
melbourne jobs in australia for immigrants jobs in australia for
international students jobs in australia for foreigners ON
http://jobsinaustralia-net.blogspot.com/  jobs in australia jobs in
australia for pakistanis jobs in australia melbourne jobs in
australia for immigrants jobs in australia for international
students jobs in australia for foreigners ON 
http://jobsinaustralia-net.blogspot.com/
jobs in australia jobs in australia for pakistanis jobs in
australia melbourne jobs in australia for immigrants jobs in
australia for international students jobs in australia for
foreigners ON http://jobsinaustralia-net.blogspot.com/  jobs in
australia jobs in australia for pakistanis jobs in australia
melbourne jobs in australia for immigrants jobs in australia for
international students jobs in australia for foreigners ON
http://jobsinaustralia-net.blogspot.com/  jobs in australia jobs in
australia for pakistanis jobs in australia melbourne jobs in
australia for immigrants jobs in australia for international
students jobs in australia for foreigners ON 
http://jobsinaustralia-net.blogspot.com/
jobs in australia jobs in australia for pakistanis jobs in
australia melbourne jobs in australia for immigrants jobs in
australia for international students jobs in australia for
foreigners ON http://jobsinaustralia-net.blogspot.com/  jobs in
australia jobs in australia for pakistanis jobs in australia
melbourne jobs in australia for immigrants jobs in australia for
international students jobs in australia for foreigners ON
http://jobsinaustralia-net.blogspot.com/  jobs in australia jobs in
australia for pakistanis jobs in australia melbourne jobs in
australia for immigrants jobs in australia for international
students jobs in australia for foreigners ON 
http://jobsinaustralia-net.blogspot.com/
jobs in australia jobs in australia for pakistanis jobs in
australia melbourne jobs in australia for immigrants jobs in
australia for international students jobs in australia for
foreigners ON http://jobsinaustralia-net.blogspot.com/  jobs in
australia jobs in australia for pakistanis jobs in australia
melbourne jobs in australia for immigrants jobs in australia for
international students jobs in australia for foreigners ON
http://jobsinaustralia-net.blogspot.com/  jobs in australia jobs in
australia for pakistanis jobs in australia melbourne jobs in
australia for immigrants jobs in australia for international
students jobs in australia for foreigners ON 
http://jobsinaustralia-net.blogspot.com/
jobs in australia jobs in australia for pakistanis jobs in

Re: sorting ascending/descending with operator.attrgetter

2010-04-01 Thread Steven D'Aprano
On Wed, 31 Mar 2010 21:54:40 -0700, Patrick Maupin wrote:

 There is a (not very subtle) difference between saying Oh, you meant a
 list, not a string (especially when the context was a discussion of
 list processing), and printing a traceback for something that nobody was
 discussing, based on a single word slip.

I wondered about that. 

I almost asked whether or not you would have reacted with less anger if I 
hadn't included the tracebacks, but decided against it. I thought that, 
given how you dropped a nuke on me for what was a very trivial social 
faux pas, you would probably interpret a question about the tracebacks as 
me being condescending and go on the attack yet again.

So far you've dropped a ton of sarcasm  on me for being the smartest, 
sharpest guy in the world, accused me of deliberately
misinterpret[ing] everything [you] write, and declared that my work-
mates (who you don't know) take great pleasure in putting me down. Such 
repeated attacks, over something as trivial as me pointing out you 
mistook list.sort for str.sort puts your comment:

I've left less poisonous workplaces for less cause.

into a completely different perspective. How little a slight does it take 
for you to decide a workplace is poisonous?

So, Patrick, here's how it goes:

I won't apologize for pointing out your error, no matter how trivial, 
because I thought, and still do, that it muddied the waters and risked 
adding confusion rather than clarity to somebody asking a very basic 
question. And for all I knew, you may have been genuinely confused 
yourself, and not just making a silly typo.

I will say that I regret including the tracebacks, not because there is 
anything wrong with doing so, but because they apparently caused you 
distress and I had no intention to do so. I am sorry that you took 
offense, it was not intended.

At the risk of offending you further, I will suggest that I'm not the 
only one who needs to apply some introspection here. If your skin is so 
thin that you react so explosively to such a minor slight, how are you 
going to react to some of the more vigorous disagreements?



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


Re: Getting a Python program to run of off a flash drive?

2010-04-01 Thread timo verbeek
On Apr 1, 12:48 am, Abethebabe abrahamalra...@gmail.com wrote:
 I wanted to know if there was a way I could get a Python program to
 run off of my flash drive as soon as the computer (Windows) detected
 the device?

 For example I could have a a simple program that would create a text
 document on the computers desktop when my flash drive is detected.

You could use Autorun.inf if your using Windows but for linux I don't
now
-- 
http://mail.python.org/mailman/listinfo/python-list


String Formatting Operations for decimals.

2010-04-01 Thread Lacrima
Hello!

I need to format a decimal (floating point) number in the following
way:
10 results in '10'
10.5 results in '10.5'
10.50 results in '10.5'
10.5678 results in 10.57

How can I achieve this using standard Python string formatting
operations?
Something like '%.2f' works almost as expected:
 '%.2f' % 10.5
'10.50'
 '%.2f' % 10.5678
'10.57'
 '%.2f' % 10
'10.00'
But I always need trailing zeros to be excluded, i.e. 10.5 should
result in '10.5' (not '10.50'), and 10 should result in '10' (not
'10.00').
So how can I do this?
Sorry for my English.
Thanks in advance.

with regards,
Maxim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting Operations for decimals.

2010-04-01 Thread Chris Rebert
On Thu, Apr 1, 2010 at 2:08 AM, Lacrima lacrima.ma...@gmail.com wrote:
 Hello!

 I need to format a decimal (floating point) number in the following
 way:
 10 results in '10'
 10.5 results in '10.5'
 10.50 results in '10.5'
 10.5678 results in 10.57

 How can I achieve this using standard Python string formatting
 operations?
 Something like '%.2f' works almost as expected:
 '%.2f' % 10.5
 '10.50'
 '%.2f' % 10.5678
 '10.57'
 '%.2f' % 10
 '10.00'
 But I always need trailing zeros to be excluded, i.e. 10.5 should
 result in '10.5' (not '10.50'), and 10 should result in '10' (not
 '10.00').
 So how can I do this?

('%.2f' % 10).rstrip('0').rstrip('.')

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting Operations for decimals.

2010-04-01 Thread Xavier Ho
Hi Maxim,

If it's the trailing zeroes you're concerned about, here's a work-around:

 ('%.2f' % 10.5678).rstrip('0')
'10.57

I'm sure there are better solutions. But this one works for your need,
right?

Cheers,'

Ching-Yun Xavier Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: cont...@xavierho.com
Website: http://xavierho.com/


On Thu, Apr 1, 2010 at 7:08 PM, Lacrima lacrima.ma...@gmail.com wrote:

 Hello!

 I need to format a decimal (floating point) number in the following
 way:
 10 results in '10'
 10.5 results in '10.5'
 10.50 results in '10.5'
 10.5678 results in 10.57

 How can I achieve this using standard Python string formatting
 operations?
 Something like '%.2f' works almost as expected:
  '%.2f' % 10.5
 '10.50'
  '%.2f' % 10.5678
 '10.57'
  '%.2f' % 10
 '10.00'
 But I always need trailing zeros to be excluded, i.e. 10.5 should
 result in '10.5' (not '10.50'), and 10 should result in '10' (not
 '10.00').
 So how can I do this?
 Sorry for my English.
 Thanks in advance.

 with regards,
 Maxim
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Generating text from a regular expression

2010-04-01 Thread Gabriel Genellina

En Wed, 31 Mar 2010 12:23:48 -0300, Paul McGuire pt...@austin.rr.com
escribió:

On Mar 31, 5:49 am, Nathan Harmston iwanttobeabad...@googlemail.com
wrote:


I have a slightly complicated/medium sized regular expression and I
want to generate all possible words that it can match (to compare
performance of regex against an acora based matcher).


The pyparsing wiki Examples page includes this regex inverter:
http://pyparsing.wikispaces.com/file/view/invRegex.py


From the module header:

# Supports:
# - {n} and {m,n} repetition, but not unbounded + or * repetition
# - ? optional elements
# - [] character ranges
# - () grouping
# - | alternation


I took the liberty of modifying your invRegex.py example, adding support
for infinite repeaters. It depends on two other modules:

mergeinf.py (from http://code.activestate.com/recipes/577041) provides the
infinite merge operation.

enumre.py provides the basic functions (merge, prod, repeat, closure)
necessary to enumerate the language generated by a given regular
expression, even if it contains unbounded repeaters like *,+.  The key is
to generate shorter strings before longer ones, so in 'a*|b*' it doesn't
get stuck generating infinite a's before any b.

By example, (a|bc)*d corresponds to this code:

  prod(
closure(
  merge(
'a',
 prod('b','c'))),
'd')

which returns an infinite generator starting with:

d
ad
aad
bcd
aaad
abcd
bcad
d
aabcd
abcad
bcaad
bcbcd
ad
aaabcd
aabcad
...


I got the idea from
http://userweb.cs.utexas.edu/users/misra/Notes.dir/RegExp.pdf

Finally, invRegexInf.py is based on your original regex parser. I only
modified the generation part, taking advantage of the above
infrastructure; the parser itself remains almost the same. It essentially
saves oneself the very tedious work of converting a regular expression
into the equivalent sequence of function calls as shown above. (I hope I
got it right: I like pyparsing a lot and use it whenever I feel it's
appropriate, but not as often as to remember the details...)

--
Gabriel Genellina

invRegexInf.py
Description: Binary data


enumre.py
Description: Binary data


mergeinf.py
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting Operations for decimals.

2010-04-01 Thread Maxim Lacrima
Hello, Chris!

Thanks for your really quick reply! It works!


On 1 April 2010 12:14, Chris Rebert c...@rebertia.com wrote:

 On Thu, Apr 1, 2010 at 2:08 AM, Lacrima lacrima.ma...@gmail.com wrote:
  Hello!
 
  I need to format a decimal (floating point) number in the following
  way:
  10 results in '10'
  10.5 results in '10.5'
  10.50 results in '10.5'
  10.5678 results in 10.57
 
  How can I achieve this using standard Python string formatting
  operations?
  Something like '%.2f' works almost as expected:
  '%.2f' % 10.5
  '10.50'
  '%.2f' % 10.5678
  '10.57'
  '%.2f' % 10
  '10.00'
  But I always need trailing zeros to be excluded, i.e. 10.5 should
  result in '10.5' (not '10.50'), and 10 should result in '10' (not
  '10.00').
  So how can I do this?

 ('%.2f' % 10).rstrip('0').rstrip('.')

 Cheers,
 Chris
 --
 http://blog.rebertia.com




-- 
with regards,
Maxim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python + OpenOffice Calc

2010-04-01 Thread egl...@gmail.com
On Apr 1, 6:53 am, rantingrick rantingr...@gmail.com wrote:

  3 fields: quantity - description of the piece bought - price

 So what is your plan...?
   * Pop up a dialog with three entrys,
   * have him fill out the three entrys,
   * then have python insert the data into the spreadsheet?
 ...Why bother messing with OO, too much trouble for me?

Totally agree with you. No need for a heavy machinery in this case.

 Then just save all the data as csv and you
 can always load it into a spreadsheet later if the IRS comes knocking,
 or you need to print a professional looking spreadsheet ;-).  Simple,
 100% python solution!

Actually, a spreadsheet based solution isn't best fit for such a task.
I'd recommend to store the data in sqlite3 (also 100% pure python as
the module is in the stdlib). CSV is good for making invoices or
something like that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Q: We have *args and **kwargs. Woud ***allargs be useful?

2010-04-01 Thread Jonathan Fine

The idioms
def f(*args, **kwargs):
# Do something.
and
args = (1, 2, 3)
kwargs = dict(a=4, b=5)
g(*args, **kwargs)
are often useful in Python.

I'm finding myself picking up /all/ the arguments and storing them for 
later use (as part of a testing framework).  So for me it would be nice 
if I could write

def f(***allargs):
 args, kwargs = allargs
 # Continue as before.

However, if we do this then 'args' in '*args' is misleading.  So I'll 
use 'sargs' (for sequence arguments) instead.


I can now write, for a suitable class Args
args = Args(1, 2, 3, a=4, b=5)
g(***args)   # Same as before.
sargs, kwargs = args
g(*sargs, **kwargs)  # Same as before.

Even better, now that Args is a class we can give it a method 'call' so that
args.call(g)
is equivalent to
g(***args)
which removes the need for the *** construct.

This reminds me of functools.partial except, of course, we've fixed all 
the arguments and left the passing of the function for later, whereas in 
partial we fix the function and some of the arguments.

http://docs.python.org/library/functools.html#functools.partial

My view are that
1.  Conceptually ***allargs is useful, but an Args class would be more 
useful (not that it need be either-or).


2.  If Args were built in , there could be performance benefits.

3.  It's clearer to write
def(*seqargs, **kwargs):
than
def(*args, **kwargs):

4.  When the Args class is used a lot, one might welcome
def(***args):
# Do something with args.
as a shortcut (and minor speedup) for
def(*seqargs, **kwargs):
args = Args(*seqargs, **kwargs)
# Do something with args.

I look forward to your comments on this.

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


Developement Question?

2010-04-01 Thread Wayne
My town office uses Microsoft operating system. They have a proprietary
accounting system that uses excel for their accounting reports.
I would like to read these report and reproduce the report so that
the report can be seen on the web. I was thinking about using xlrd and
xlwt along with some sort of software for building the web pages. I
use linux only and do not use Microsoft.
Q. Does python have to be installed on there computer to run the script?

Q. Am I approaching this the wrong way? If so, what would be a better
approach?


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


newbie with a encoding question, please help

2010-04-01 Thread Mister Yu
hi experts,

i m new to python, i m writing crawlers to extract data from some
chinese websites, and i run into a encoding problem.

i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4'
which is encoded in gb2312, but i have no idea of how to convert it
back to utf-8

to re-create this one is easy:

this will work

 su = u中文.encode('gb2312')
 su
u
 print su.decode('gb2312')
中文- (same as the original string)


but this doesn't,why
===
 su = u'\xd6\xd0\xce\xc4'
 su
u'\xd6\xd0\xce\xc4'
 print su.decode('gb2312')
Traceback (most recent call last):
  File console, line 1, in module
UnicodeEncodeError: 'ascii' codec can't encode characters in position
0-3: ordinal not in range(128)
===

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


Re: associative array

2010-04-01 Thread Javier Montoya
On Mar 31, 7:36 pm, Gary Herron gher...@digipen.edu wrote:
 JavierMontoyawrote:
  Dear all,

  I'm a newbie in python and would be acknowledge if somebody could shed
  some light on associative arrays.
  More precisely, I would like to create a multi-dimensional associative
  array. I have for example a list of students which are identified
  uniquely by their student IDs. Additionally, for each student I have
  some information: FirstName, LastName, etc.

  The array would have then the following form:
  [StudentID] = [FirstName][LastName][Telephone]...[ ... ]

  I would like to be able to access a field directly by using a
  StudentID
  [StudentID][FirstName]
  [StudentID][LastName]

  How could I manipulate such an array (create the array, add elements,
  access data)?

  Best wishes

 Create a class for student with attributes for ID, FirstName, LastName, etc.

   class Student:
       def __init__(self, id, FirstName, ...):
           self.id = id
           self.FirstName = FirstName
           ...

 then whenever you create a student object, use a dictionary to associate
 the object with its is
   AA = {} # An empty dictionary
   s = Student(...)
   AA[s.id] = s
   ... and repeat for many students...

 Then to access a student's object given an id:
   s = AA[id]
   print s.id, s.FirstName, s.LastName, ...

 I'd *not* call this a multi-dimension association, but rather just an
 association between student objects and their ids.

 Hope that helps,

 Gary Herron

 --
 Gary Herron, PhD.
 Department of Computer Science
 DigiPen Institute of Technology
 (425) 895-4418

Dear all,

Thanks for your suggestions, it worked! As Gary suggested, I created a
'student' class and mapped its objects to a dictionary.
Is it possible to sort the dictionary by the student's grades in
descending order?

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


Re: associative array

2010-04-01 Thread Chris Rebert
On Thu, Apr 1, 2010 at 3:58 AM, Javier Montoya jmonto...@gmail.com wrote:
 On Mar 31, 7:36 pm, Gary Herron gher...@digipen.edu wrote:
 JavierMontoyawrote:
  Dear all,

  I'm a newbie in python and would be acknowledge if somebody could shed
  some light on associative arrays.
  More precisely, I would like to create a multi-dimensional associative
  array. I have for example a list of students which are identified
  uniquely by their student IDs. Additionally, for each student I have
  some information: FirstName, LastName, etc.

  The array would have then the following form:
  [StudentID] = [FirstName][LastName][Telephone]...[ ... ]

  I would like to be able to access a field directly by using a
  StudentID
  [StudentID][FirstName]
  [StudentID][LastName]

  How could I manipulate such an array (create the array, add elements,
  access data)?

  Best wishes

 Create a class for student with attributes for ID, FirstName, LastName, etc.

   class Student:
       def __init__(self, id, FirstName, ...):
           self.id = id
           self.FirstName = FirstName
           ...

 then whenever you create a student object, use a dictionary to associate
 the object with its is
   AA = {} # An empty dictionary
   s = Student(...)
   AA[s.id] = s
   ... and repeat for many students...

 Then to access a student's object given an id:
   s = AA[id]
   print s.id, s.FirstName, s.LastName, ...

 I'd *not* call this a multi-dimension association, but rather just an
 association between student objects and their ids.

 Hope that helps,

 Gary Herron

 --
 Gary Herron, PhD.
 Department of Computer Science
 DigiPen Institute of Technology
 (425) 895-4418

 Dear all,

 Thanks for your suggestions, it worked! As Gary suggested, I created a
 'student' class and mapped its objects to a dictionary.
 Is it possible to sort the dictionary by the student's grades in
 descending order?

Dictionaries are not ordered collections, so they themselves cannot be sorted.

However, if you want a list of students sorted in the manner you stated:
class_rank = list(garys_dictionary.values())
class_rank.sort(key=lambda student: student.grade, reverse=True)

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie with a encoding question, please help

2010-04-01 Thread Chris Rebert
2010/4/1 Mister Yu eryan...@gmail.com:
 hi experts,

 i m new to python, i m writing crawlers to extract data from some
 chinese websites, and i run into a encoding problem.

 i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4'
 which is encoded in gb2312,

No! Instances of type 'unicode' (i.e. strings with a leading 'u')
***aren't encoded at all***.

 but i have no idea of how to convert it
 back to utf-8

To convert u'\xd6\xd0\xce\xc4' to UTF-8, do u'\xd6\xd0\xce\xc4'.encode('utf-8')

 to re-create this one is easy:

 this will work
 
 su = u中文.encode('gb2312')
 su
 u
 print su.decode('gb2312')
 中文    - (same as the original string)

 
 but this doesn't,why
 ===
 su = u'\xd6\xd0\xce\xc4'
 su
 u'\xd6\xd0\xce\xc4'
 print su.decode('gb2312')
You can't decode a unicode string, it's already been decoded!

One decodes a bytestring to get a unicode string.
One **encodes** a unicode string to get a bytestring.

So the last line of your example should be:
print su.encode('gb2312')

Only call .encode() on things of type 'unicode'.
Only call .decode() on things of type 'str'.
[When using Python 2.x that is. Python 3.x renames the types in question.]

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: associative array

2010-04-01 Thread Peter Otten
Javier Montoya wrote:

 Is it possible to sort the dictionary by the student's grades in
 descending order?

You cannot sort dictionaries, but you can put dictionary items into a list 
and then sort that.

Assumming that you have a dictionary student_dict that maps student IDs to 
Student instances and a function get_grade() to find a student's grade you'd 
do

def get_grade(student):
return course[student.student_id].grade # or whatever it takes

students_by_grade = sorted(student_dict.itervalues(), key=get_grade, 
reverse=True)

for student in students_by_grade:
print student.first_name, student.last_name

However, problems like the above are normally handled best using a SQL 
database, so I recommend that you have a look at

http://docs.python.org/library/sqlite3.html

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


Re: newbie with a encoding question, please help

2010-04-01 Thread Mister Yu
On Apr 1, 7:22 pm, Chris Rebert c...@rebertia.com wrote:
 2010/4/1 Mister Yu eryan...@gmail.com:

  hi experts,

  i m new to python, i m writing crawlers to extract data from some
  chinese websites, and i run into a encoding problem.

  i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4'
  which is encoded in gb2312,

 No! Instances of type 'unicode' (i.e. strings with a leading 'u')
 ***aren't encoded at all***.

  but i have no idea of how to convert it
  back to utf-8

 To convert u'\xd6\xd0\xce\xc4' to UTF-8, do 
 u'\xd6\xd0\xce\xc4'.encode('utf-8')



  to re-create this one is easy:

  this will work
  
  su = u中文.encode('gb2312')
  su
  u
  print su.decode('gb2312')
  中文    - (same as the original string)

  
  but this doesn't,why
  ===
  su = u'\xd6\xd0\xce\xc4'
  su
  u'\xd6\xd0\xce\xc4'
  print su.decode('gb2312')

 You can't decode a unicode string, it's already been decoded!

 One decodes a bytestring to get a unicode string.
 One **encodes** a unicode string to get a bytestring.

 So the last line of your example should be:
 print su.encode('gb2312')

 Only call .encode() on things of type 'unicode'.
 Only call .decode() on things of type 'str'.
 [When using Python 2.x that is. Python 3.x renames the types in question.]

 Cheers,
 Chris
 --http://blog.rebertia.com

hi, thanks for the tips.

but i m still not very sure how to convert a unicode object  **
u'\xd6\xd0\xce\xc4 ** back to 中文 the string it supposed to be?

thanks.

sorry i m really new to python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: associative array

2010-04-01 Thread Harishankar
On Wed, 31 Mar 2010 09:40:30 -0700, Javier Montoya wrote:

 Dear all,
 
 I'm a newbie in python and would be acknowledge if somebody could shed
 some light on associative arrays.
 More precisely, I would like to create a multi-dimensional associative
 array. I have for example a list of students which are identified
 uniquely by their student IDs. Additionally, for each student I have
 some information: FirstName, LastName, etc.
 
 The array would have then the following form: [StudentID] =
 [FirstName][LastName][Telephone]...[ ... ]
 
 I would like to be able to access a field directly by using a StudentID
 [StudentID][FirstName]
 [StudentID][LastName]
 
 How could I manipulate such an array (create the array, add elements,
 access data)?
 
 Best wishes

I know this is not a direct answer, but in your case I would probably use 
a database, because it is the easiest and most standardized way to access 
such types of data. If you don't want something heavyweight, use sqlite 
with in-memory databases/persistent file.

Look at sqlite3 module in python.





-- 
Harishankar (http://harishankar.org http://literaryforums.org)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie with a encoding question, please help

2010-04-01 Thread Chris Rebert
On Thu, Apr 1, 2010 at 4:38 AM, Mister Yu eryan...@gmail.com wrote:
 On Apr 1, 7:22 pm, Chris Rebert c...@rebertia.com wrote:
 2010/4/1 Mister Yu eryan...@gmail.com:
  hi experts,

  i m new to python, i m writing crawlers to extract data from some
  chinese websites, and i run into a encoding problem.

  i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4'
  which is encoded in gb2312,
snip
 hi, thanks for the tips.

 but i m still not very sure how to convert a unicode object  **
 u'\xd6\xd0\xce\xc4 ** back to 中文 the string it supposed to be?

Ah, my apologies! I overlooked something (sorry, it's early in the
morning where I am).
What you have there is ***really*** screwy. It's the 2 Chinese
characters, encoded in gb2312, and then somehow cast *directly* into a
'unicode' string (which ought never to be done).

In answer to your original question (after some experimentation):
gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4'])
unicode_string = gb2312_bytes.decode('gb2312')
utf8_bytes = unicode_string.encode('utf-8') #as you wanted

If possible, I'd look at the code that's giving you that funky
string in the first place and see if it can be fixed to give you
either a proper bytestring or proper unicode string rather than the
bastardized mess you're currently having to deal with.

Apologies again and Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie with a encoding question, please help

2010-04-01 Thread Stefan Behnel

Mister Yu, 01.04.2010 13:38:

i m still not very sure how to convert a unicode object  **
u'\xd6\xd0\xce\xc4 ** back to 中文 the string it supposed to be?


You are confused. '\xd6\xd0\xce\xc4' is an encoded byte string, not a 
unicode string. The fact that you have it stored in a unicode string 
implies that something in your code (or in a library) has done an incorrect 
conversion from bytes to unicode that did not take into account the real 
character set in use. So you end up with a completely meaningless unicode 
string.


Please show us the code that does the conversion to a unicode string.

Stefan

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


Re: newbie with a encoding question, please help

2010-04-01 Thread Mister Yu
On Apr 1, 8:13 pm, Chris Rebert c...@rebertia.com wrote:
 On Thu, Apr 1, 2010 at 4:38 AM, Mister Yu eryan...@gmail.com wrote:
  On Apr 1, 7:22 pm, Chris Rebert c...@rebertia.com wrote:
  2010/4/1 Mister Yu eryan...@gmail.com:
   hi experts,

   i m new to python, i m writing crawlers to extract data from some
   chinese websites, and i run into a encoding problem.

   i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4'
   which is encoded in gb2312,
 snip
  hi, thanks for the tips.

  but i m still not very sure how to convert a unicode object  **
  u'\xd6\xd0\xce\xc4 ** back to 中文 the string it supposed to be?

 Ah, my apologies! I overlooked something (sorry, it's early in the
 morning where I am).
 What you have there is ***really*** screwy. It's the 2 Chinese
 characters, encoded in gb2312, and then somehow cast *directly* into a
 'unicode' string (which ought never to be done).

 In answer to your original question (after some experimentation):
 gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4'])
 unicode_string = gb2312_bytes.decode('gb2312')
 utf8_bytes = unicode_string.encode('utf-8') #as you wanted

 If possible, I'd look at the code that's giving you that funky
 string in the first place and see if it can be fixed to give you
 either a proper bytestring or proper unicode string rather than the
 bastardized mess you're currently having to deal with.

 Apologies again and Cheers,
 Chris
 --http://blog.rebertia.com

Hi Chris,

thanks for the great tips! it works like a charm.

i m using the Scrapy project(http://doc.scrapy.org/intro/
tutorial.html) to write my crawler, when it extract data with xpath,
it puts the chinese characters directly into the unicode object.

thanks again chris, and have a good april fool day.

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


Re: decorators only when __debug__ == True

2010-04-01 Thread MRAB

Steven D'Aprano wrote:

On Thu, 01 Apr 2010 00:27:51 +0100, MRAB wrote:


A decorator shouldn't call the function it's decorating.

*raises eyebrow*

Surely, in the general case, a decorator SHOULD call the function it is
decorating? I'm sure you know that, but your wording is funny and could
confuse the OP.


What I mean is that the function that's doing the decorating shouldn't
call the function; it's the locally-defined wrapper function that calls
the decorated function.


Ah, gotcha, that makes sense. Now I understand the distinction you were 
making. Thank you for the clarification.



I had the following idea: define the terms 'decorator', 'decoration' and
'decoratee'. The decorator applies the decoration to the decoratee. The
decoratee is the function defined locally in the decorator.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Developement Question?

2010-04-01 Thread MRAB

Wayne wrote:

My town office uses Microsoft operating system. They have a proprietary
accounting system that uses excel for their accounting reports.
I would like to read these report and reproduce the report so that
the report can be seen on the web. I was thinking about using xlrd and
xlwt along with some sort of software for building the web pages. I
use linux only and do not use Microsoft.
Q. Does python have to be installed on there computer to run the script?


If you can copy the spreadsheet files to your machine then you can run the
script on your machine.


Q. Am I approaching this the wrong way? If so, what would be a better
approach?



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


Re: decorators only when __debug__ == True

2010-04-01 Thread Steve Holden
MRAB wrote:
 Steven D'Aprano wrote:
 On Thu, 01 Apr 2010 00:27:51 +0100, MRAB wrote:

 A decorator shouldn't call the function it's decorating.
 *raises eyebrow*

 Surely, in the general case, a decorator SHOULD call the function it is
 decorating? I'm sure you know that, but your wording is funny and could
 confuse the OP.

 What I mean is that the function that's doing the decorating shouldn't
 call the function; it's the locally-defined wrapper function that calls
 the decorated function.

 Ah, gotcha, that makes sense. Now I understand the distinction you
 were making. Thank you for the clarification.

 I had the following idea: define the terms 'decorator', 'decoration' and
 'decoratee'. The decorator applies the decoration to the decoratee. The
 decoratee is the function defined locally in the decorator.

It would make more sense (to me, at least) if the decoratee were the
function passed as an argument to the decorator.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: newbie with a encoding question, please help

2010-04-01 Thread Stefan Behnel

Mister Yu, 01.04.2010 14:26:

On Apr 1, 8:13 pm, Chris Rebert wrote:

gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4'])
unicode_string = gb2312_bytes.decode('gb2312')
utf8_bytes = unicode_string.encode('utf-8') #as you wanted


Simplifying this hack a bit:

gb2312_bytes = u'\xd6\xd0\xce\xc4'.encode('ISO-8859-1')
unicode_string = gb2312_bytes.decode('gb2312')
utf8_bytes = unicode_string.encode('utf-8')

Although I have to wonder why you want a UTF-8 encoded byte string as 
output instead of Unicode.




If possible, I'd look at the code that's giving you that funky
string in the first place and see if it can be fixed to give you
either a proper bytestring or proper unicode string rather than the
bastardized mess you're currently having to deal with.


thanks for the great tips! it works like a charm.


I hope you're aware that it's a big ugly hack, though. You should really 
try to fix your input instead.




i m using the Scrapy project(http://doc.scrapy.org/intro/
tutorial.html) to write my crawler, when it extract data with xpath,
it puts the chinese characters directly into the unicode object.


My guess is that the HTML page you are parsing is broken and doesn't 
specify its encoding. In that case, all that scrapy can do is guess, and it 
seems to have guessed incorrectly.


You should check if there is a way to tell scrapy about the expected page 
encoding, so that it can return correctly decoded unicode strings directly, 
instead of resorting to dirty hacks that may or may not work depending on 
the page you are parsing.


Stefan

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


Python 3.1, object, and setattr()

2010-04-01 Thread Ethan Furman

Greetings!

Perhaps I woke up too early this morning, but this behaviour has me baffled:

Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit 
(Intel)] on win32

Type help, copyright, credits or license for more information.

-- test = object()

-- setattr(test, 'example', 123)
Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: 'object' object has no attribute 'example'

Shouldn't setattr() be creating the 'example' attribute?  Any tips 
greatly appreciated!


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


Re: sorting ascending/descending with operator.attrgetter

2010-04-01 Thread Patrick Maupin
On Apr 1, 1:54 am, Steven D'Aprano
ste...@remove.this.cybersource.com.au wrote:
 At the risk of offending you further, I will suggest that I'm not the
 only one who needs to apply some introspection here. If your skin is so
 thin that you react so explosively to such a minor slight, how are you
 going to react to some of the more vigorous disagreements?

I think, if you go back and read other threads, you will find that a)
I react fine to even very vigorous technical disagreements, and b) my
reaction to you in particular (which, yes, introspection does show
that I need to not react right away) is because of an induced
sensitivity.  Perhaps I'll see my allergist.

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


Re: decorators only when __debug__ == True

2010-04-01 Thread Steve Howell
On Apr 1, 6:16 am, Steve Holden st...@holdenweb.com wrote:
 MRAB wrote:

  I had the following idea: define the terms 'decorator', 'decoration' and
  'decoratee'. The decorator applies the decoration to the decoratee. The
  decoratee is the function defined locally in the decorator.

 It would make more sense (to me, at least) if the decoratee were the
 function passed as an argument to the decorator.


Me too.  I do like the idea of coming up with a consistent terminology.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.1, object, and setattr()

2010-04-01 Thread Steve Howell
On Apr 1, 6:46 am, Ethan Furman et...@stoneleaf.us wrote:
 Greetings!

 Perhaps I woke up too early this morning, but this behaviour has me baffled:

 Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
 (Intel)] on win32
 Type help, copyright, credits or license for more information.

 -- test = object()

 -- setattr(test, 'example', 123)
 Traceback (most recent call last):
    File stdin, line 1, in module
 AttributeError: 'object' object has no attribute 'example'

 Shouldn't setattr() be creating the 'example' attribute?  Any tips
 greatly appreciated!


On 2.6.2 the error seems to be limited to instances of object.  If you
subclass object, you are fine.  I do not know why that is so; I'm just
verifying that the behavior you see is not limited to 3.1.1.

 Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
 [GCC 4.3.3] on linux2
 Type help, copyright, credits or license for more
information.
  class Foo(object): pass
 ...
  test = Foo()
  setattr(test, 'example', 123)
  test.example
 123
  test = object()
  setattr(test, 'example', 123)
 Traceback (most recent call last):
   File stdin, line 1, in module
 AttributeError: 'object' object has no attribute 'example'

It's probably good to subclass object anyway, with something like:

  class Record(object):
  pass

But I do not know your use case.

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


Re: Python 3.1, object, and setattr()

2010-04-01 Thread Steve Holden
Ethan Furman wrote:
 Greetings!
 
 Perhaps I woke up too early this morning, but this behaviour has me
 baffled:
 
 Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
 (Intel)] on win32
 Type help, copyright, credits or license for more information.
 
 -- test = object()
 
 -- setattr(test, 'example', 123)
 Traceback (most recent call last):
   File stdin, line 1, in module
 AttributeError: 'object' object has no attribute 'example'
 
 Shouldn't setattr() be creating the 'example' attribute?  Any tips
 greatly appreciated!
 
It's not just object, and it's not just the setattr() function. It's not
even just Python 3.1 for that matter! Later Python 2 implementations
have the same issue.

 x = 1
 setattr(x, 'example', 123)
Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: 'int' object has no attribute 'example'
 x.example = 123
Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: 'int' object has no attribute 'example'


There are limits to what you can do with the built-in types. No matter
how hard Python tries to make them look the same, ultimately the
built-in types are implemented differently from the types you create
yourself.

For efficiency reasons the attributes of the built-ins are stored in a
different way (that's more accessible to the C implementation) than
those of the declared types.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: sorting ascending/descending with operator.attrgetter

2010-04-01 Thread Patrick Maupin
On Apr 1, 12:50 am, Steve Holden st...@holdenweb.com wrote:
  I can well imagine that everybody who has to work with you thoroughly
   enjoys proving you wrong as often as possible.

 I am glad I wasn't drinking when I read this. Liquid in one's nose is so
 uncomfortable.

Well, in that case, I'm glad you enjoyed it.  It's hard to know when
to put a disclaimer on these things.  Others might not find the same
sorts of things funny, and the very act of putting a disclaimer often
promises more than it delivers, so I think it's pretty much just
caveat reader.

 I guess we have to value the good that's in Steven (few would deny that
 he *is* technically very competent) and try and ignore his more annoying
 side.

Well, I suppose there are two coping strategies.  Ignoring him (yes, I
need to do that more), and also, reading more carefully before
posting.  The latter is always a good thing, but on the other hand it
takes more mental effort.  Yes, it's better for posterity, but someone
reading the thread later and seeing what is written in context will
probably figure out what is meant, even if there are a few mistakes.
The extra effort shifts the balance from will this help the OP? to
if this email were read completely devoid of external context, how
many ways are there to mis-interpret it, and how much time am I
willing to spend reducing that number, when it's impossible to get it
to zero, anyway?

 I have toyed many times with the idea of giving a presentation at PyCon
 called something like Humanity 101. It would include such advice as
 When I say 'use soap' I am not talking about the Simple Object Access
 Protocol and Being wrong is usually survivable; offending a homicidal
 maniac often isn't.

 Perhaps I should just add it to the Holden Web course schedule?

Well, I haven't killed anybody yet; OTOH a few events from my
childhood taught me that there are really only two kinds of people:
those who could kill under the right circumstances, and those who
haven't figured it out yet.  So, yes, that might be a good idea ;-)

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


Re: Python 3.1, object, and setattr()

2010-04-01 Thread Steve Holden
Ethan Furman wrote:
 Greetings!
 
 Perhaps I woke up too early this morning, but this behaviour has me
 baffled:
 
 Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
 (Intel)] on win32
 Type help, copyright, credits or license for more information.
 
 -- test = object()
 
 -- setattr(test, 'example', 123)
 Traceback (most recent call last):
   File stdin, line 1, in module
 AttributeError: 'object' object has no attribute 'example'
 
 Shouldn't setattr() be creating the 'example' attribute?  Any tips
 greatly appreciated!
 
By the way, the solution is to create a subclass of object (which in
Python 3 simply requires you to declare a class! In Python 2 you'd have
to explicitly subclass object, or (equivalently) set your class's
metaclass to type with

__metaclass__ = type


regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: CGI templating with python

2010-04-01 Thread Someone Something
Cheetah would work, but it would be a major pain to debug (I hate those 500
Server Error pages) something django (as mentioned above) or turbogears
(with Kid) would get you rolling quickly.

On Wed, Mar 31, 2010 at 8:38 PM, KB ke...@nekotaku.com wrote:

 Hi there,

 Years ago I wrote a LAMP app using python. I find I need a simple web
 data entry tool to store records (stock research) and when I enter a
 stock ticker, to pull up all the past research I have done. I am
 imagining fields like ticker, date, pulldown menus for various
 options, long text for comments etc..

 It's a very light weight application, so I was wondering if using
 something like Cheetah is the best way to do this?

 Or should I research Zope further or are there any other suggestions?

 Environment:
 - Python 2.5 (w/ MySQLdb)
 - MySQL 5.1
 - Windows Vista

 Many thanks in advance!
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: newbie with a encoding question, please help

2010-04-01 Thread Mister Yu
On Apr 1, 9:31 pm, Stefan Behnel stefan...@behnel.de wrote:
 Mister Yu, 01.04.2010 14:26:

  On Apr 1, 8:13 pm, Chris Rebert wrote:
  gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4'])
  unicode_string = gb2312_bytes.decode('gb2312')
  utf8_bytes = unicode_string.encode('utf-8') #as you wanted

 Simplifying this hack a bit:

  gb2312_bytes = u'\xd6\xd0\xce\xc4'.encode('ISO-8859-1')
  unicode_string = gb2312_bytes.decode('gb2312')
  utf8_bytes = unicode_string.encode('utf-8')

 Although I have to wonder why you want a UTF-8 encoded byte string as
 output instead of Unicode.

  If possible, I'd look at the code that's giving you that funky
  string in the first place and see if it can be fixed to give you
  either a proper bytestring or proper unicode string rather than the
  bastardized mess you're currently having to deal with.

  thanks for the great tips! it works like a charm.

 I hope you're aware that it's a big ugly hack, though. You should really
 try to fix your input instead.

  i m using the Scrapy project(http://doc.scrapy.org/intro/
  tutorial.html) to write my crawler, when it extract data with xpath,
  it puts the chinese characters directly into the unicode object.

 My guess is that the HTML page you are parsing is broken and doesn't
 specify its encoding. In that case, all that scrapy can do is guess, and it
 seems to have guessed incorrectly.

 You should check if there is a way to tell scrapy about the expected page
 encoding, so that it can return correctly decoded unicode strings directly,
 instead of resorting to dirty hacks that may or may not work depending on
 the page you are parsing.

 Stefan

Hi Stefan,

i don't think the page is broken or somehow, you can take a look at
the page http://www.7176.com/Sections/Genre/Comedy  , it's kinda like
a chinese IMDB rip off

from what i can see from the source code of the page header, it
contains the coding info:
HTMLheadmeta http-equiv=Content-Type content=text/html;
charset=gb2312 /meta http-equiv=Content-Language content=zh-CN /
meta content=all name=robots /meta name=author
content=admin(at)7176.com /meta name=Copyright content=www.
7176.com / meta content=类别为 剧情 的电影列表 第1页 name=keywords /TITLE
类别为 剧情 的电影列表 第1页/TITLELINK href=http://www.7176.com/images/
pro.css rel=stylesheet/HEAD

maybe i should take a look at the source code of Scrapy, but i m just
not more than a week's newbie of python. not sure if i can understand
the source.

earlier Chris's walk around is looking pretty well until it meets some
string like this:
 su = u'一二三四 12345 一二三四'
 su
u'\u4e00\u4e8c\u4e09\u56db 12345 \u4e00\u4e8c\u4e09\u56db'
 gb2312_bytes = ''.join([chr(ord(c)) for c in u'\u4e00\u4e8c\u4e09\u56db 
 12345 \u4e00\u4e8c\u4e09\u56db'])
Traceback (most recent call last):
  File stdin, line 1, in module
ValueError: chr() arg not in range(256)

the digis doesn't get encoded so it messes up the code.

any ideas?

once again, thanks everybody's help

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


Re: sort array, apply rearrangement to second

2010-04-01 Thread Steve Howell
On Mar 31, 1:09 pm, Raymond Hettinger pyt...@rcn.com wrote:
 On Mar 30, 4:25 pm, s...@sig.for.address (Victor Eijkhout) wrote:

  I have two arrays, made with numpy. The first one has values that I want
  to use as sorting keys; the second one needs to be sorted by those keys.
  Obviously I could turn them into a dictionary  of pairs and sort by the
  first member, but I think that's not very efficient, at least in space,
  and this needs to be done as efficiently as possible.

 Alf's recommendation is clean and correct.  Just make a list of
 tuples.

 FWIW, here's a little hack that does the work for you:

  values = ['A', 'B', 'C', 'D', 'E']
  keys = [50, 20, 40, 10, 30]
  keyiter = iter(keys)
  sorted(values, key=lambda k: next(keyiter))

 ['D', 'B', 'E', 'C', 'A']


Another option:

[values[i] for i in sorted(range(len(keys)), key=lambda i: keys[i])]

Sort the indexes according to keys values, then use indexes to get the
values.

It might read more clearly when broken out into two lines:

 sorted_indexes = sorted(range(len(keys)), key = lambda i: keys[i])
 sorted_indexes
[3, 1, 4, 2, 0]
 [values[i] for i in sorted_indexes]
['D', 'B', 'E', 'C', 'A']

The advantage of Raymond's solution is that he only creates one new
Python list, whereas my solutions create an intermediate Python list
of integers.  I don't think my solution really is that space-wasteful,
though, since by the time the second list gets created, any internal
intermediate lists from CPython's sorted() implementation will
probably have been cleaned up.



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


Re: CGI templating with python

2010-04-01 Thread KB

 Django will probably get you where you want to go the fastest:

    http://www.djangoproject.com/

 In particular, its admin interface will probably automatically generate a 
 usable
 UI for you without your having to write many templates at all.

Robert,

Thank you very very much. I had a brief peruse of django last night
and it does indeed look like what I am after! Will take me some
time :) to delve into it deeper but I wanted to thank you!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Developement Question?

2010-04-01 Thread KB
On Apr 1, 3:34 am, Wayne infotech...@fairpoint.net wrote:
 My town office uses Microsoft operating system. They have a proprietary
 accounting system that uses excel for their accounting reports.
 I would like to read these report and reproduce the report so that
 the report can be seen on the web. I was thinking about using xlrd and
 xlwt along with some sort of software for building the web pages. I
 use linux only and do not use Microsoft.
 Q. Does python have to be installed on there computer to run the script?

 Q. Am I approaching this the wrong way? If so, what would be a better
 approach?

Wayne, check out google group python-excel.

They are very helpful there, and I believe there are threads on how to
compile what you are looking for into a .exe for just such a situation
(Disclaimer: I am far from an expert, so I may have misunderstood from
the python-excel thread if python is/isn't required on the target
machine once the .exe is built, but try that group - John Machin is
very responsive)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-01 Thread Den
On Mar 30, 10:56 am, Steve Holden st...@holdenweb.com wrote:
 John Nagle wrote:
  Chris Rebert wrote:
  On Tue, Mar 30, 2010 at 8:40 AM, gentlestone tibor.b...@hotmail.com
  wrote:
  Hi, how can I write the popular C/JAVA syntax in Python?

  Java example:
     return (a==b) ? 'Yes' : 'No'

  My first idea is:
     return ('No','Yes')[bool(a==b)]

  Is there a more elegant/common python expression for this?

  Yes, Python has ternary operator-like syntax:
  return ('Yes' if a==b else 'No')

  Note that this requires a recent version of Python.

      Who let the dogs in?  That's awful syntax.

 Yes, that's deliberately awful syntax. Guido designed it that way to
 ensure that people didn't aver-use it, thereby reducing the readability
 of Python applications. Speaking purely personally I hardly ever use it,
 but don't dislike it.

 regards
  Steve
 --
 Steve Holden           +1 571 484 6266   +1 800 494 3119
 See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
 Holden Web LLC                http://www.holdenweb.com/
 UPCOMING EVENTS:        http://holdenweb.eventbrite.com/

I've been following this thread for a few days now.  My thoughts are
that, in view of a long known widely used syntax for this operator,
python's syntax seems like change for change sake.  If current
programing paradigm provides that particular trinary operator, why
should python's be different from the previously well known one.

For instance, no reasonable language designer would, now, use post-fix
(I know about Forth) or allow only +=, -=, /=, etc. assignments ONLY.
(Just as no reasonable car designer would put the accelerator pedal on
the left.)  There are conventions which should span products.  Yes
python has the trinary operator and it's not going to change, but this
seems like a bit of petulance on the part of the designer.

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


Re: Q: We have *args and **kwargs. Woud ***allargs be useful?

2010-04-01 Thread Jon Clements
On 1 Apr, 10:57, Jonathan Fine j.f...@open.ac.uk wrote:
 The idioms
      def f(*args, **kwargs):
          # Do something.
 and
      args = (1, 2, 3)
      kwargs = dict(a=4, b=5)
      g(*args, **kwargs)
 are often useful in Python.

 I'm finding myself picking up /all/ the arguments and storing them for
 later use (as part of a testing framework).  So for me it would be nice
 if I could write
      def f(***allargs):
           args, kwargs = allargs
           # Continue as before.

 However, if we do this then 'args' in '*args' is misleading.  So I'll
 use 'sargs' (for sequence arguments) instead.

 I can now write, for a suitable class Args
      args = Args(1, 2, 3, a=4, b=5)
      g(***args)   # Same as before.
      sargs, kwargs = args
      g(*sargs, **kwargs)  # Same as before.

 Even better, now that Args is a class we can give it a method 'call' so that
      args.call(g)
 is equivalent to
      g(***args)
 which removes the need for the *** construct.

 This reminds me of functools.partial except, of course, we've fixed all
 the arguments and left the passing of the function for later, whereas in
 partial we fix the function and some of the arguments.
      http://docs.python.org/library/functools.html#functools.partial

 My view are that
 1.  Conceptually ***allargs is useful, but an Args class would be more
 useful (not that it need be either-or).

 2.  If Args were built in , there could be performance benefits.

 3.  It's clearer to write
          def(*seqargs, **kwargs):
 than
          def(*args, **kwargs):

 4.  When the Args class is used a lot, one might welcome
          def(***args):
              # Do something with args.
 as a shortcut (and minor speedup) for
          def(*seqargs, **kwargs):
              args = Args(*seqargs, **kwargs)
              # Do something with args.

 I look forward to your comments on this.

 --
 Jonathan

I'm not sure this'll catch on, it'll be interesting to see other
comments.
However, I believe you can get the behaviour you desire something
like:

import inspect

class AllArgs(object):
def __init__(self, func):
self._func = func
self._spec = inspect.getargspec(func)
self._nposargs = len(self._spec.args)
def __call__(self, *args, **kwdargs):
self._func.func_globals['Args'] = (args[self._nposargs:],
kwdargs)
return self._func(*args[:self._nposargs])

@AllArgs
def test():
print Args

@AllArgs
def test2(a, b):
print a, b, Args

test(1, 2, 3, 4, 5, a=3, b=5)
test2(1, 2, 3, 4, 5, c=7)

Done quickly, probably buggy, but does provide 'Args', but without
further work
swallows any *'s and **'s and might ignore defaults (hideously
untested)



hth

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


Re: subprocess only good for win32?

2010-04-01 Thread wukong
On Mar 31, 3:47 pm, Martin v. Loewis mar...@v.loewis.de wrote:
  WindowsError: [Error 14001] The application has failed to start
  because its side-by-side configuration is incorrect. Please see the
  application event log for more detail

 This is a configuration error on your system. The application you are
 trying to start is incorrectly installed - it's not only that Python
 can't start it, but nobody can.

 Regards,
 Martin

but python runs happy otherwise, only this call to subprocess resulted
in an err.  does anyone know for sure subprocess runs on win64?  or
any others like, popen does?
thanks
wk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess only good for win32?

2010-04-01 Thread wukong
On Mar 31, 3:47 pm, Martin v. Loewis mar...@v.loewis.de wrote:
  WindowsError: [Error 14001] The application has failed to start
  because its side-by-side configuration is incorrect. Please see the
  application event log for more detail

 This is a configuration error on your system. The application you are
 trying to start is incorrectly installed - it's not only that Python
 can't start it, but nobody can.

 Regards,
 Martin

nad also as i mentioned previously, it runs great on win32.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-01 Thread Steve Holden
Den wrote:
[...]
 I've been following this thread for a few days now.  My thoughts are
 that, in view of a long known widely used syntax for this operator,
 python's syntax seems like change for change sake.  If current
 programing paradigm provides that particular trinary operator, why
 should python's be different from the previously well known one.
 
Because the long known widely used syntax has been responsible for
some of the most incomprehensible and buggy code in the known universe. \
 For instance, no reasonable language designer would, now, use post-fix
 (I know about Forth) or allow only +=, -=, /=, etc. assignments ONLY.
 (Just as no reasonable car designer would put the accelerator pedal on
 the left.)  There are conventions which should span products.  Yes
 python has the trinary operator and it's not going to change, but this
 seems like a bit of petulance on the part of the designer.
 
That argument could easily be extended to suggesting that there should
be no new languages at all. Guido made the specific choice of this
syntax precisely to try and ensure that the ternary (not trinary)
operator wasn't abused the way it has been in C (and later C#). He is a
language designer with a fine sense of readability, and I personally
respect his decision.

This StackOverflow thread

http://stackoverflow.com/questions/1763543/ternary-operator-associativity-in-c-can-i-rely-on-it

is just one example of the time that gets wasted.

But then I suppose that this thread just exemplifies that people will
find something else to waste their time on if you don't encourage them
to abuse the ternary operator.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Q: We have *args and **kwargs. Woud ***allargs be useful?

2010-04-01 Thread Jonathan Fine

Jon Clements wrote:


I'm not sure this'll catch on, it'll be interesting to see other
comments.
However, I believe you can get the behaviour you desire something
like:

import inspect

class AllArgs(object):
def __init__(self, func):
self._func = func
self._spec = inspect.getargspec(func)
self._nposargs = len(self._spec.args)
def __call__(self, *args, **kwdargs):
self._func.func_globals['Args'] = (args[self._nposargs:],
kwdargs)
return self._func(*args[:self._nposargs])

@AllArgs
def test():
print Args

@AllArgs
def test2(a, b):
print a, b, Args

test(1, 2, 3, 4, 5, a=3, b=5)
test2(1, 2, 3, 4, 5, c=7)

Done quickly, probably buggy, but does provide 'Args', but without
further work
swallows any *'s and **'s and might ignore defaults (hideously
untested)


Thank you for your interest, Jon.

According to http://docs.python.org/library/inspect.html we have that 
func_globals is the global namespace in which this function was defined.


Hence we have
 def f(): pass
...
 f.func_globals is globals()
True
 f.func_globals ['x'] = 3
 x
3


I don't yet understand what your code is intended to do, but I'm fairly 
sure you're not wishing to 'monkey-patch' a global namespace of a module.


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


Re: subprocess only good for win32?

2010-04-01 Thread Steve Holden
wukong wrote:
 On Mar 31, 3:47 pm, Martin v. Loewis mar...@v.loewis.de wrote:
 WindowsError: [Error 14001] The application has failed to start
 because its side-by-side configuration is incorrect. Please see the
 application event log for more detail
 This is a configuration error on your system. The application you are
 trying to start is incorrectly installed - it's not only that Python
 can't start it, but nobody can.

 Regards,
 Martin
 
 but python runs happy otherwise, only this call to subprocess resulted
 in an err.  does anyone know for sure subprocess runs on win64?  or
 any others like, popen does?
 thanks
 wk

Subprocess runs another program. It's the program you are running that's
giving the error, Python is merely reporting it.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: decorators only when __debug__ == True

2010-04-01 Thread MRAB

Steve Holden wrote:

MRAB wrote:

Steven D'Aprano wrote:

On Thu, 01 Apr 2010 00:27:51 +0100, MRAB wrote:


A decorator shouldn't call the function it's decorating.

*raises eyebrow*

Surely, in the general case, a decorator SHOULD call the function it is
decorating? I'm sure you know that, but your wording is funny and could
confuse the OP.


What I mean is that the function that's doing the decorating shouldn't
call the function; it's the locally-defined wrapper function that calls
the decorated function.

Ah, gotcha, that makes sense. Now I understand the distinction you
were making. Thank you for the clarification.


I had the following idea: define the terms 'decorator', 'decoration' and
'decoratee'. The decorator applies the decoration to the decoratee. The
decoratee is the function defined locally in the decorator.


It would make more sense (to me, at least) if the decoratee were the
function passed as an argument to the decorator.


Oops, you're right! What I meant was that the _decoration_ is the
function defined locally in the decorator.
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess only good for win32?

2010-04-01 Thread Michel Claveau - MVP
Hi!

 side-by-side configuration is incorrect

Others have given you an explanation.

A possibility: you use a DLL directly, without having installed.
That is OK with some DLL, and no OK with others DLL.

@-salutations
-- 
Michel Claveau 


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


jobs in canada jobs in canada for pakistanis jobs in canada for foreigners jobs in canada hotels jobs in canada for accountants canada jobs canada job bank on http://jobsincanada-net.

2010-04-01 Thread saima81
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
jobs in canada jobs in canada for pakistanis jobs in canada for
foreigners jobs in canada hotels jobs in canada for accountants
canada jobs canada job bank on  http://jobsincanada-net.blogspot.com/
v
-- 
http://mail.python.org/mailman/listinfo/python-list


no module named exceptions?

2010-04-01 Thread Joaquin Abian
In python 3.1,

 import exceptions
Traceback (most recent call last):
  File pyshell#6, line 1, in module
import exceptions
ImportError: No module named exceptions

in 2.6 no exception is raised
It should be the same in 3.1, isnt it?

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


Re: no module named exceptions?

2010-04-01 Thread Shashwat Anand
There i no module named 'exceptions' in python 2.6 as well as python 3.1
What are you expecting ?

On Thu, Apr 1, 2010 at 10:42 PM, Joaquin Abian gatoyga...@gmail.com wrote:

 In python 3.1,

  import exceptions
 Traceback (most recent call last):
  File pyshell#6, line 1, in module
import exceptions
 ImportError: No module named exceptions

 in 2.6 no exception is raised
 It should be the same in 3.1, isnt it?

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

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


Re: no module named exceptions?

2010-04-01 Thread Tommy Grav
This is what he is expecting. Importing exceptions works fine in 2.6.4, not so
in python 3.1. 

Python 2.6.4 (r264:75706, Nov  3 2009, 18:12:54) 
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type help, copyright, credits or license for more information.
 import exceptions
 

Tommy


On Apr 1, 2010, at 1:29 PM, Shashwat Anand wrote:

 There i no module named 'exceptions' in python 2.6 as well as python 3.1 What 
 are you expecting ?
 
 On Thu, Apr 1, 2010 at 10:42 PM, Joaquin Abian gatoyga...@gmail.com wrote:
 In python 3.1,
 
  import exceptions
 Traceback (most recent call last):
  File pyshell#6, line 1, in module
import exceptions
 ImportError: No module named exceptions
 
 in 2.6 no exception is raised
 It should be the same in 3.1, isnt it?
 
 Joaquin
 --
 http://mail.python.org/mailman/listinfo/python-list
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Python 3.1, object, and setattr()

2010-04-01 Thread Terry Reedy

On 4/1/2010 10:16 AM, Steve Howell wrote:

On Apr 1, 6:46 am, Ethan Furmanet...@stoneleaf.us  wrote:

On 2.6.2 the error seems to be limited to instances of object.  If you
subclass object, you are fine.  I do not know why that is so;


As the other Steve said, object is a built-in class; user-defined 
subclasses of object are user-defined classes. (And all other built-in 
classes are built-in subclasses of object, at least in 3.x.)


Python objects can have either a fixed or variable set of attributes. By 
default, instances of user classes have an attribute dictionary 
(__dict__) for a variable set of attributes.


 a = A()
 a.a = 3
 a.a
3
 a.__dict__
{'a': 3}

The exception is when '__slots__ = xxx' is part of the class definition. 
It instances then have a fixed set of attributes.


 class C(): __slots__ = ()

 c = C()
 c.a = 1
Traceback (most recent call last):
  File pyshell#8, line 1, in module
c.a = 1
AttributeError: 'C' object has no attribute 'a'

The error message means that 'a' is not in the fixed set of instance 
attributes (as defined by __slots__) for class C.


In general, instances of built-in classes do not have such attribute 
dictionaries and one their attribute set is fixed (and often empty). It 
is as if built-in classes have '__slots__ = xxx' as part of their 
definition. In particular, object and others act like they have 
'__slots__ = ()', which means they have no instance attributes.


There are two exceptions among built-in classes that I know of: type and 
'function', (whose instances are user-defined functions).


 def f(): pass

 f.__dict__
{} # standard dict just as with user class instances

Instances of type are more complicated:

 C.__dict__
dict_proxy object at 0x00F682F0
 C.z = 3
 C.z
3

so the dict_proxy for user classes is writable

but
 int.__dict__
dict_proxy object at 0x00F5CDD0
 int.z = 3
Traceback (most recent call last):
  File pyshell#18, line 1, in module
int.z = 3
TypeError: can't set attributes of built-in/extension type 'int'

wheres for builtins, it is not.

Terry Jan Reedy


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


question on namedtuple

2010-04-01 Thread hetchkay
Hi,
For purposes I don't want to go into here, I have the following code:
def handleObj(obj):
  if isinstance(obj, MyType):
 return obj.handle()
  elif isinstance(obj, (list, tuple, set)):
 return obj.__class__(map (handleObj, obj))
  elif isinstance(obj, dict):
 return obj.__class__((handleObj(k), handleObj(v)) for k, v in
obj.items())
  else:
 return obj

This works fine except if obj is a namedtuple. A namedtuple object has
different constructor signature from tuple:
 tuple([1,2])
(1,2)
 collections.namedtuple(sample, a, b)([1, 2])
Traceback (most recent call last):
  File CommandConsole, line 1, in module
TypeError: __new__() takes exactly 3 arguments (2 given)
 collections.namedtuple(sample, a, b)(1, 2)
sample(a=1, b=2)

Is there any easy way of knowing that the obj is a namedtuple and not
a plain tuple [so that I could use obj.__class__(*map(handleObj, obj))
instead of obj.__class__(map(handleObj, obj)) ].

Thanks in advance for your help.

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


folks, what's wrong with this?

2010-04-01 Thread Ani
Hi All:

I am just a beginner in python. Can anyone please tell me what is
wrong with this piece of code?

import copy
class BaseDummyObject(object):

def __init__(self):
pass

def __getattr__(self, item):
try:
return self.__dict__.__getitem__(item)
except KeyError:
print Attribute Error: attr %s of class %s non-existent!
%(item,
 
self.__class__.__name__)
class DummyObject(BaseDummyObject):
pass


def main():
bar = 3
obj = DummyObject()
obj.foo = bar
obj.me = obj

newobj = copy.deepcopy(obj)


if __name__ == __main__:
main()

So when I do this, I get:

Attribute Error: attr __deepcopy__ of class DummyObject non-existent!
Attribute Error: attr __getnewargs__ of class DummyObject non-
existent!
Traceback (most recent call last):
  File C:\Workspace\QA3.0\Python_Lib\Mobidia\RemoteManager
\test_code.py, line 39, in module
main()
  File C:\Workspace\QA3.0\Python_Lib\Mobidia\RemoteManager
\test_code.py, line 30, in main
newobj = copy.deepcopy(obj)
  File C:\Python26\lib\copy.py, line 181, in deepcopy
rv = reductor(2)
TypeError: 'NoneType' object is not callable

Any help will be really appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.1, object, and setattr()

2010-04-01 Thread Ethan Furman

Many thanks for the replies, and especially for the very detailed
explanation.  Makes much more sense now.

~Ethan~

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


Re: folks, what's wrong with this?

2010-04-01 Thread Robert Kern

On 2010-04-01 13:56 PM, Ani wrote:

Hi All:

I am just a beginner in python. Can anyone please tell me what is
wrong with this piece of code?

import copy
class BaseDummyObject(object):

 def __init__(self):
 pass

 def __getattr__(self, item):
 try:
 return self.__dict__.__getitem__(item)
 except KeyError:
 print Attribute Error: attr %s of class %s non-existent!
%(item,

self.__class__.__name__)


You need to raise an AttributeError here. Otherwise, it implicitly returns None 
for all attributes not in the __dict__ and thus confusing the copy.deepcopy() code.


--
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Re: no module named exceptions?

2010-04-01 Thread Chris Rebert
 On Thu, Apr 1, 2010 at 10:42 PM, Joaquin Abian gatoyga...@gmail.com wrote:
 In python 3.1,

  import exceptions
 Traceback (most recent call last):
  File pyshell#6, line 1, in module
import exceptions
 ImportError: No module named exceptions

 in 2.6 no exception is raised
 It should be the same in 3.1, isnt it?

On Thu, Apr 1, 2010 at 10:37 AM, Tommy Grav tg...@mac.com wrote:
 This is what he is expecting. Importing exceptions works fine in 2.6.4, not
 so
 in python 3.1.
 Python 2.6.4 (r264:75706, Nov  3 2009, 18:12:54)
 [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
 Type help, copyright, credits or license for more information.
 import exceptions


It appears to have been removed between Python 3.1.2
(http://docs.python.org/py3k/modindex.html#cap-E) and Python 3.2a0
(http://docs.python.org/dev/py3k/modindex.html#cap-E). Exactly why, I
don't know. I wasn't able to locate anything about it in a quick scan
of the Python 3000 PEPs.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question on namedtuple

2010-04-01 Thread Chris Rebert
On Thu, Apr 1, 2010 at 11:35 AM, hetchkay hetch...@gmail.com wrote:
 Hi,
 For purposes I don't want to go into here, I have the following code:
 def handleObj(obj):
  if isinstance(obj, MyType):
     return obj.handle()
  elif isinstance(obj, (list, tuple, set)):
     return obj.__class__(map (handleObj, obj))
  elif isinstance(obj, dict):
     return obj.__class__((handleObj(k), handleObj(v)) for k, v in
 obj.items())
  else:
     return obj

 This works fine except if obj is a namedtuple. A namedtuple object has
 different constructor signature from tuple:
 tuple([1,2])
 (1,2)
 collections.namedtuple(sample, a, b)([1, 2])
 Traceback (most recent call last):
  File CommandConsole, line 1, in module
 TypeError: __new__() takes exactly 3 arguments (2 given)
 collections.namedtuple(sample, a, b)(1, 2)
 sample(a=1, b=2)

 Is there any easy way of knowing that the obj is a namedtuple and not
 a plain tuple [so that I could use obj.__class__(*map(handleObj, obj))
 instead of obj.__class__(map(handleObj, obj)) ].

It's very slightly brittle, but a good heuristic is probably:

if isinstance(obj, tuple) and all(hasattr(obj, attr_name) for \
attr_name in ('_make','_fields','_replace','_asdict')):
return obj.__class__(*map(handleObj, obj))

I couldn't find/think of a more direct/reliable method. Though perhaps
there's some more obscure but accurate method.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: no module named exceptions?

2010-04-01 Thread Gary Herron

Joaquin Abian wrote:

In python 3.1,

  

import exceptions


Traceback (most recent call last):
  File pyshell#6, line 1, in module
import exceptions
ImportError: No module named exceptions

in 2.6 no exception is raised
It should be the same in 3.1, isnt it?

Joaquin
  


In 2.x, the exceptions module was imported automatically, so there was 
never a need to explicitly import it.

For example:
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type help, copyright, credits or license for more information.
 print ImportError
type 'exceptions.ImportError'


In Python 3.x, it appears the same effect is achieved by putting the 
Exceptions in the builtin module

For example:
Python 3.1.1+ (r311:74480, Nov  2 2009, 14:49:22)
[GCC 4.4.1] on linux2
Type help, copyright, credits or license for more information.
 print(ImportError)
class 'ImportError'

And another example:
 import builtins
 print(builtins.ImportError)
class 'ImportError'


--
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

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


Re: no module named exceptions?

2010-04-01 Thread Ned Deily
In article 
l2g50697b2c1004011245l80c169e6k5be038e8ca75b...@mail.gmail.com,
 Chris Rebert c...@rebertia.com wrote:

  On Thu, Apr 1, 2010 at 10:42 PM, Joaquin Abian gatoyga...@gmail.com wrote:
  In python 3.1,
 
   import exceptions
  Traceback (most recent call last):
   File pyshell#6, line 1, in module
 import exceptions
  ImportError: No module named exceptions
 
  in 2.6 no exception is raised
  It should be the same in 3.1, isnt it?
 
 On Thu, Apr 1, 2010 at 10:37 AM, Tommy Grav tg...@mac.com wrote:
  This is what he is expecting. Importing exceptions works fine in 2.6.4, not
  so
  in python 3.1.
  Python 2.6.4 (r264:75706, Nov  3 2009, 18:12:54)
  [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
  Type help, copyright, credits or license for more information.
  import exceptions
 
 
 It appears to have been removed between Python 3.1.2
 (http://docs.python.org/py3k/modindex.html#cap-E) and Python 3.2a0
 (http://docs.python.org/dev/py3k/modindex.html#cap-E). Exactly why, I
 don't know. I wasn't able to locate anything about it in a quick scan
 of the Python 3000 PEPs.

The exceptions module doesn't exist in Python 3 but the documentation 
had not been cleaned up until recently:

http://bugs.python.org/issue7590

-- 
 Ned Deily,
 n...@acm.org

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


Re: question on namedtuple

2010-04-01 Thread Peter Otten
hetchkay wrote:

 For purposes I don't want to go into here, I have the following code:
 def handleObj(obj):
   if isinstance(obj, MyType):
  return obj.handle()
   elif isinstance(obj, (list, tuple, set)):
  return obj.__class__(map (handleObj, obj))
   elif isinstance(obj, dict):
  return obj.__class__((handleObj(k), handleObj(v)) for k, v in
 obj.items())
   else:
  return obj
 
 This works fine except if obj is a namedtuple. A namedtuple object has
 different constructor signature from tuple:
 tuple([1,2])
 (1,2)
 collections.namedtuple(sample, a, b)([1, 2])
 Traceback (most recent call last):
   File CommandConsole, line 1, in module
 TypeError: __new__() takes exactly 3 arguments (2 given)
 collections.namedtuple(sample, a, b)(1, 2)
 sample(a=1, b=2)
 
 Is there any easy way of knowing that the obj is a namedtuple and not
 a plain tuple [so that I could use obj.__class__(*map(handleObj, obj))
 instead of obj.__class__(map(handleObj, obj)) ].

I don't think there is a safe way to do this short of a comprehensive list 
of namedtuple classes. In practice it may be sufficient to check the duck 
type of the tuple subclass, e. g.:

elif isinstance(obj, (list, set)):
return obj.__class__(map(handleObj, obj))
elif isinstance(obj, tuple):
try:
make = obj._make
except AttributeError:
make = obj.__class__
return make(handleObj(item) for item in obj)

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


off topic but please forgive me me and answer

2010-04-01 Thread superpollo

how much is one half times one half?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python + OpenOffice Calc

2010-04-01 Thread rantingrick
On Apr 1, 4:38 am, egl...@gmail.com egl...@gmail.com wrote:

 Actually, a spreadsheet based solution isn't best fit for such a task.
 I'd recommend to store the data in sqlite3 (also 100% pure python as
 the module is in the stdlib). CSV is good for making invoices or
 something like that.

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


Re: subprocess only good for win32?

2010-04-01 Thread Piet van Oostrum
 wukong novacomp...@gmail.com (w) wrote:

w also subprocess.py clearly says
w 
w import sys
w mswindows = (sys.platform == win32)
w 

It may sound strange, but even in 64-bit Python on Win64,
sys.plattform==win32. 

You can check that subprocess is working, e.g. with 
subprocess.call('dir', shell=True)
-- 
Piet van Oostrum p...@vanoostrum.org
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
Nu Fair Trade woonwaar op http://www.zylja.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-01 Thread Tim Chase

superpollo wrote:

how much is one half times one half?



Uh, did you try it at the python prompt?  If not, here's the answer:

 0.1b * 0.1b = 0.01b

Now all you need is to find the recent thread that converts 
binary floats to decimal floats ;-)


-tkc


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


Re: folks, what's wrong with this?

2010-04-01 Thread Ani
On Apr 1, 12:10 pm, Robert Kern robert.k...@gmail.com wrote:
 On 2010-04-01 13:56 PM, Ani wrote:



  Hi All:

  I am just a beginner in python. Can anyone please tell me what is
  wrong with this piece of code?

  import copy
  class BaseDummyObject(object):

       def __init__(self):
           pass

       def __getattr__(self, item):
           try:
               return self.__dict__.__getitem__(item)
           except KeyError:
               print Attribute Error: attr %s of class %s non-existent!
  %(item,

  self.__class__.__name__)

 You need to raise an AttributeError here. Otherwise, it implicitly returns 
 None
 for all attributes not in the __dict__ and thus confusing the copy.deepcopy() 
 code.


Thanks Robert. So I raised the exception and now everything looks
good. So what's happening here? When a certain attribute is not
available in the __dict__ and an exception is raised, who's catching
it?

Ani

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


Re: folks, what's wrong with this?

2010-04-01 Thread Robert Kern

On 2010-04-01 16:52 PM, Ani wrote:

On Apr 1, 12:10 pm, Robert Kernrobert.k...@gmail.com  wrote:

On 2010-04-01 13:56 PM, Ani wrote:




Hi All:



I am just a beginner in python. Can anyone please tell me what is
wrong with this piece of code?



import copy
class BaseDummyObject(object):



  def __init__(self):
  pass



  def __getattr__(self, item):
  try:
  return self.__dict__.__getitem__(item)
  except KeyError:
  print Attribute Error: attr %s of class %s non-existent!
%(item,



self.__class__.__name__)


You need to raise an AttributeError here. Otherwise, it implicitly returns None
for all attributes not in the __dict__ and thus confusing the copy.deepcopy() 
code.



Thanks Robert. So I raised the exception and now everything looks
good. So what's happening here? When a certain attribute is not
available in the __dict__ and an exception is raised, who's catching
it?


copy.deepcopy(), in this case, or one of the functions it calls. You can use 
traceback.print_stack() to see who is attempting to get the attribute. It is 
checking for certain methods on the object which control how the object gets 
seralized. copy.deepcopy() uses the same mechanism as pickle to serialize and 
reconstruct the object in memory.


--
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


C-style static variables in Python?

2010-04-01 Thread kj


When coding C I have often found static local variables useful for
doing once-only run-time initializations.  For example:

int foo(int x, int y, int z) {

  static int first_time = TRUE;
  static Mongo *mongo;
  if (first_time) {
mongo = heavy_lifting_at_runtime();
first_time = FALSE;
  }

  return frobnicate(mongo, x, y, z);
}

In this case, the static variable mongo is initialized only once
(at most).

What I like most about this is that it obviates the need for a
global variable to hold the persistent value (I avoid globals like
the plague, especially in Python).  It also nicely encapsulates
the logic that determines whether initialization is required.

The best way I've found to achieve a similar effect in (procedural)
Python defines the function as a closure.  For example, here's a
function that keeps track of (and prints out) how many times it
has been called:

 def make_spam():
... counter = [0]
... def _():
... counter[0] += 1
... print counter[0]
... return _
... 
 spam = make_spam()
 spam()
1
 spam()
2
 spam()
3

(Too bad that one can't stick the whole def inside parentheses and
call the function right there, like one can do with JavaScript.)

Another approach would be to stuff the static values in the function's
__dict__.  This is less satisfactory than the closure approach
because the pseudo-static variable is accessible from outside
the function, but the code is arguably a little more straightforward,
and one does not end up with the now useless one-time closure-generating
function kicking around.  Here's another version of the function
above:

 def spam():
... d = spam.__dict__
... if not 's' in spam.__dict__:
... spam.s = 1 
... print spam.s
... spam.s += 1
... 
 spam()
1
 spam()
2
 spam()
3

Besides the external accessibility issue, I don't like explictly
coding the name of the function within the function.  Is there any
way to have the function access its own __dict__ without having to
explicitly code its name in its body?  E.g., is there some generic
special variable that, within a function, refers to the function
object itself?

I'm sure that there are many other ways to skin this cat, especially
if one starts definining fancy callable classes and whatnot.  But
is there a better *simple* way to achieve C-style static locals in
Python that does not require a lot of extra machinery?

TIA!

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


Re: C-style static variables in Python?

2010-04-01 Thread Chris Rebert
On Thu, Apr 1, 2010 at 3:34 PM, kj no.em...@please.post wrote:
 When coding C I have often found static local variables useful for
 doing once-only run-time initializations.
snip
 Another approach would be to stuff the static values in the function's
 __dict__.  This is less satisfactory than the closure approach
 because the pseudo-static variable is accessible from outside
 the function, but the code is arguably a little more straightforward,
 and one does not end up with the now useless one-time closure-generating
 function kicking around.  Here's another version of the function
 above:

 def spam():
 ...     d = spam.__dict__
 ...     if not 's' in spam.__dict__:
 ...         spam.s = 1
 ...     print spam.s
 ...     spam.s += 1
 ...
 spam()
 1
 spam()
 2
 spam()
 3

 Besides the external accessibility issue, I don't like explictly
 coding the name of the function within the function.  Is there any
 way to have the function access its own __dict__ without having to
 explicitly code its name in its body?  E.g., is there some generic
 special variable that, within a function, refers to the function
 object itself?

Nope. It's been proposed in that past
(http://www.python.org/dev/peps/pep-3130/), but that proposal was
rejected.

 I'm sure that there are many other ways to skin this cat, especially
 if one starts definining fancy callable classes and whatnot.  But
 is there a better *simple* way to achieve C-style static locals in
 Python that does not require a lot of extra machinery?

You can abuse the default argument value mechanism:

def spam(s_cell=[1]):
s = s_cell[0]
print s
s_cell[0] += 1

It's a bit less ugly when the value itself is mutable, which isn't the
case here with the integer.

Personally, I hate such abuse with a passion; I think a global
variable is clearest.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Pydev 1.5.6 Released (Django Integration)

2010-04-01 Thread Fabio Zadrozny
Hi All,

Pydev 1.5.6 has been released

Details on Pydev: http://pydev.org
Details on its development: http://pydev.blogspot.com

Release Highlights:
---

* Django integration:

* New Django project can be created through wizards
* Can set an existing project as a Django project (right-click
project  pydev  set as django project)
* Can remove Django project config (right-click project  django 
remove django project config)
* Custom actions can be passed to the configured manage.py through
ctrl+2+dj django_action -- if no action is passed, will open dialog to
choose from a list of previously used commands.
* Predefined/custom actions can be used through right-clicking the
project  django  select custom action
* manage.py location and settings module configured
* Django shell (with code-completion, history, etc) available
* Run/Debug as Django available
* See: http://pydev.org/manual_adv_django.html for more details

* Find/Replace:

* The search in open files is no longer added in the find/replace
dialog and now works through Ctrl+2+s word_to_find (in the Pydev
editor) and if no word is passed, the editor selection is used

* Go to definiton:

* Properly works with unsaved files (so, it will work when
searching for a definition on an unsaved file)
* Properly working with eclipse 3.6 (having FileStoreEditorInput
as the editor input)

* Editor:

* Automatically closing literals.
* Removing closing pair on backspace on literal
* Improved heuristics for automatically closing (, [ and {
* Removing closing pairs on backspace on (,[ and {
* ctrl+2+sl (sl comes from 'split lines' -- can be used to add a
new line after each comma in the selection
* ctrl+2+is (is comes from 'import string' -- can be used to
transform the selected import into a string with dots

* General:

* Code-completion properly working on relative import with an alias.
* Fixed racing issue that could deadlock pydev (under really hard
to reproduce circumstances)
* Removing reloading code while debugging until (if) it becomes
more mature in the python side
* Fixed issue where a new project created didn't have the source
folder correctly set
* Text selection in double click no longer has weird behavior
* Local refactoring working on files not in the PYTHONPATH
* Edit properly working on string substitution variables
* Using with statement on python 2.5 no longer makes lines wrong in the AST



What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python, Jython
and IronPython development -- making Eclipse a first class Python IDE
-- It comes with many goodies such as code completion, syntax
highlighting, syntax analysis, refactor, debug and many others.


Cheers,

-- 
Fabio Zadrozny
--
Software Developer

Aptana
http://aptana.com/python

Pydev - Python Development Environment for Eclipse
http://pydev.org
http://pydev.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-style static variables in Python?

2010-04-01 Thread Steve Holden
Chris Rebert wrote:
 On Thu, Apr 1, 2010 at 3:34 PM, kj no.em...@please.post wrote:
 When coding C I have often found static local variables useful for
 doing once-only run-time initializations.
 snip
 Another approach would be to stuff the static values in the function's
 __dict__.  This is less satisfactory than the closure approach
 because the pseudo-static variable is accessible from outside
 the function, but the code is arguably a little more straightforward,
 and one does not end up with the now useless one-time closure-generating
 function kicking around.  Here's another version of the function
 above:

 def spam():
 ... d = spam.__dict__
 ... if not 's' in spam.__dict__:
 ... spam.s = 1
 ... print spam.s
 ... spam.s += 1
 ...
 spam()
 1
 spam()
 2
 spam()
 3

 Besides the external accessibility issue, I don't like explictly
 coding the name of the function within the function.  Is there any
 way to have the function access its own __dict__ without having to
 explicitly code its name in its body?  E.g., is there some generic
 special variable that, within a function, refers to the function
 object itself?
 
 Nope. It's been proposed in that past
 (http://www.python.org/dev/peps/pep-3130/), but that proposal was
 rejected.
 
 I'm sure that there are many other ways to skin this cat, especially
 if one starts definining fancy callable classes and whatnot.  But
 is there a better *simple* way to achieve C-style static locals in
 Python that does not require a lot of extra machinery?
 
 You can abuse the default argument value mechanism:
 
 def spam(s_cell=[1]):
 s = s_cell[0]
 print s
 s_cell[0] += 1
 
 It's a bit less ugly when the value itself is mutable, which isn't the
 case here with the integer.
 
 Personally, I hate such abuse with a passion; I think a global
 variable is clearest.

But the real problem is that the OP is insisting on using purely
procedural Python when the problem is screaming for an object-oriented
answer.

If the function were instead a method then the instance namespace would
be the logical place to store the required data.

regards
 Steve
regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: C-style static variables in Python?

2010-04-01 Thread Terry Reedy

On 4/1/2010 6:34 PM, kj wrote:



When coding C I have often found static local variables useful for
doing once-only run-time initializations.  For example:

int foo(int x, int y, int z) {

   static int first_time = TRUE;
   static Mongo *mongo;
   if (first_time) {
 mongo = heavy_lifting_at_runtime();
 first_time = FALSE;
   }

   return frobnicate(mongo, x, y, z);


Global var or class or closure such as below (obviously untested ;=):

make_foo()
  mongo = heavy_lifting_at_runtime();
  def _(x,y,z):
return frobnicate(mongo, x, y, z)
  return _
foo = make_foo
del make_foo # to make sure it is *never* called again ;

Now you only have foo with a hard-to-access private object and no 
first_time checks when you call it.


Terry Jan Reedy

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


Re: C-style static variables in Python?

2010-04-01 Thread Patrick Maupin
On Apr 1, 6:10 pm, Steve Holden st...@holdenweb.com wrote:
 Chris Rebert wrote:
  Personally, I hate such abuse with a passion; I think a global
  variable is clearest.

 But the real problem is that the OP is insisting on using purely
 procedural Python when the problem is screaming for an object-oriented
 answer.

 If the function were instead a method then the instance namespace would
 be the logical place to store the required data.

In some situations I will use either the default parameter
initialization Chris mentioned, or the closure mechanism that the OP
presented, but only on code that I am optimizing for speed (local
variable lookups, even in nested functions, being much faster than
global or instance lookups).  If it doesn't need to go fast, globals
or instance variables are the way to go.

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


Re: off topic but please forgive me me and answer

2010-04-01 Thread Patrick Maupin
On Apr 1, 4:42 pm, Tim Chase python.l...@tim.thechases.com wrote:
 superpollo wrote:
  how much is one half times one half?

 Uh, did you try it at the python prompt?  If not, here's the answer:

   0.1b * 0.1b = 0.01b

 Now all you need is to find the recent thread that converts
 binary floats to decimal floats ;-)

 -tkc

I thought it was 0b0.1 * 0b0.1 == 0b0.01

Otherwise, you might get it confused with hexadecimal floats :D
-- 
http://mail.python.org/mailman/listinfo/python-list


How to run python without python

2010-04-01 Thread Spencer
Is there a way to developing a script on linux and give it
to someone on microsoft, so that they could run it on microsoft
without installing python?

Wayne

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


Re: How to run python without python

2010-04-01 Thread Krister Svanlund
On Fri, Apr 2, 2010 at 1:36 AM, Spencer infotech...@fairpoint.net wrote:
 Is there a way to developing a script on linux and give it
 to someone on microsoft, so that they could run it on microsoft
 without installing python?

 Wayne

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


Short answer: No.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-style static variables in Python?

2010-04-01 Thread Steve Holden
Terry Reedy wrote:
 On 4/1/2010 6:34 PM, kj wrote:


 When coding C I have often found static local variables useful for
 doing once-only run-time initializations.  For example:

 int foo(int x, int y, int z) {

static int first_time = TRUE;
static Mongo *mongo;
if (first_time) {
  mongo = heavy_lifting_at_runtime();
  first_time = FALSE;
}

return frobnicate(mongo, x, y, z);
 
 Global var or class or closure such as below (obviously untested ;=):
 
 make_foo()
   mongo = heavy_lifting_at_runtime();
   def _(x,y,z):
 return frobnicate(mongo, x, y, z)
   return _
 foo = make_foo

I suspect you mean

foo = make_foo()

 del make_foo # to make sure it is *never* called again ;
 
 Now you only have foo with a hard-to-access private object and no
 first_time checks when you call it.
 
 Terry Jan Reedy
 
I don't think I'd ever want to use such an obscure technique in a
program. You might want to consider using functools.wraps to make sure
that the foo function looks right.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: How to run python without python

2010-04-01 Thread Chris Rebert
On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund
krister.svanl...@gmail.com wrote:
 On Fri, Apr 2, 2010 at 1:36 AM, Spencer infotech...@fairpoint.net wrote:
 Is there a way to developing a script on linux and give it
 to someone on microsoft, so that they could run it on microsoft
 without installing python?

 Short answer: No.

Long answer:
No indeed. But if he were to have a Windows computer, he could
generate a standalone executable from a Python program using one of
the following tools:
py2exe: http://www.py2exe.org/
PyInstaller: http://www.pyinstaller.org/

But one can't generate such a standalone executable for a different
operating system from that which one's computer runs.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-01 Thread David Robinow
On Thu, Apr 1, 2010 at 7:34 PM, Patrick Maupin pmau...@gmail.com wrote:
 On Apr 1, 4:42 pm, Tim Chase python.l...@tim.thechases.com wrote:
 superpollo wrote:
  how much is one half times one half?

 Uh, did you try it at the python prompt?  If not, here's the answer:

   0.1b * 0.1b = 0.01b

 Now all you need is to find the recent thread that converts
 binary floats to decimal floats ;-)

 -tkc

 I thought it was 0b0.1 * 0b0.1 == 0b0.01

 Otherwise, you might get it confused with hexadecimal floats :D
 Well, my python says:

$ python -c print 1/2 * 1/2
0

 But that's not what I learned in grade school.
(Maybe I should upgrade to 3.1?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Good Intermediate Tutorials

2010-04-01 Thread Abethebabe
I've recently finished reading A Byte Of Python and have the basics of
Python down. I want to continue practice but I'm unsure what I can do.
So I started looking for tutorials to open my mind a little, but
everything I come across are beginner tutorials that cover the same
topics...over and over.

Can anyone point me to good Intermediate tutorials, that don't make
use of libraries and such (so I can get really comfortable with the
core language.) Maybe even the source code of some simple Python
applications, so I can observe and learn the code myself.

Really appreciative of any help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-01 Thread Tim Chase

David Robinow wrote:

$ python -c print 1/2 * 1/2
0

 But that's not what I learned in grade school.
(Maybe I should upgrade to 3.1?)


That's because you need to promote one of them to a float so you 
get a floating-point result:


   1/2 * 1/2
  0
   1/2 * 1/2.0
  0.0

Oh...wait ;-)

-tkc



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


Browser-based MMOG web framework

2010-04-01 Thread Steve
Hi, I could use some advice on my project.

It's a browser-based MMOG: The High Seas (working title)

Basically it is a trading game set in 1600s or 1700s ... inspirations:
Patrician 3, Mine Things, Space Rangers 2, ...

Travel between cities takes several days: game updates trading ship
positions every 10 minutes.  Apart from that it handles player input
to buy/sell goods, if their ship is in port.

I want the game logic and world state data storage on a webserver,
with players connecting via web browser.  Also, I want to make an
admin mode client for me to keep track of the world and add changes
to game world stuff.

I want to use Python but I haven't ever used it in a web context.

http://wiki.python.org/moin/WebFrameworks lists several different
options for Python Web Frameworks: Django, Grok, Pylons, TurboGears,
web2py, Zope.  I've heard of Django and Grok...that's about my level
of knowledge here.

My question: can any of these frameworks help me with what I'm trying
to do?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good Intermediate Tutorials

2010-04-01 Thread rantingrick
On Apr 1, 7:25 pm, Abethebabe abrahamalra...@gmail.com wrote:
 I've recently finished reading A Byte Of Python and have the basics of
 Python down. I want to continue practice but I'm unsure what I can do.
 So I started looking for tutorials to open my mind a little, but
 everything I come across are beginner tutorials that cover the same
 topics...over and over.

 Can anyone point me to good Intermediate tutorials, that don't make
 use of libraries and such (so I can get really comfortable with the
 core language.) Maybe even the source code of some simple Python
 applications, so I can observe and learn the code myself.

 Really appreciative of any help!


Try Dive into Python, great tut!
http://diveintopython.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-style static variables in Python?

2010-04-01 Thread Alf P. Steinbach

* kj:

When coding C I have often found static local variables useful for
doing once-only run-time initializations.  For example:

int foo(int x, int y, int z) {

  static int first_time = TRUE;
  static Mongo *mongo;
  if (first_time) {
mongo = heavy_lifting_at_runtime();
first_time = FALSE;
  }

  return frobnicate(mongo, x, y, z);
}

In this case, the static variable mongo is initialized only once
(at most).

What I like most about this is that it obviates the need for a
global variable to hold the persistent value (I avoid globals like
the plague, especially in Python).  It also nicely encapsulates
the logic that determines whether initialization is required.


In C++ you just write

  int foo( int x, int y, int z )
  {
  static Mongo* const mongo = heavy_lifting_at_runtime();
  return frobnicate( mongo, x, y, z );
  }




The best way I've found to achieve a similar effect in (procedural)
Python defines the function as a closure.  For example, here's a
function that keeps track of (and prints out) how many times it
has been called:


def make_spam():

... counter = [0]
... def _():
... counter[0] += 1
... print counter[0]
... return _
... 

spam = make_spam()
spam()

1

spam()

2

spam()

3

(Too bad that one can't stick the whole def inside parentheses and
call the function right there, like one can do with JavaScript.)


Off the cuff, Py3:

class Spam:
def __init__( self ):
self._counter = 0

def __call__( self ):
self._counter += 1
print( counter )

spam = Spam()
spam()
spam()
spam()


[snip]

I'm sure that there are many other ways to skin this cat, especially
if one starts definining fancy callable classes and whatnot.


As I see it it's the closure that's fancy, and the class that's simple and 
direct.



 But
is there a better *simple* way to achieve C-style static locals in
Python that does not require a lot of extra machinery?


If you often need this functionality you might consider a general decorator that 
supplies the function with a self argument, e.g. like this:



example
#Py3

class Object: pass

def static_initialization( init_func ):
def self_aware( f ):
def wrapped( *args, **kwargs ):
return f( f, *args, **kwargs )
init_func( f )
return wrapped
o = Object()
o.body = self_aware
return o


# Example usage:

@static_initialization
def spam( self ):
self.counter = 0

@spam.body
def spam( self ):
self.counter += 1
print( self.counter )

spam()
spam()
spam()
/example


But as mentioned, a class is (at least IMHO) simpler and more direct.



Cheers  hth.,

- Alf (department of disingenious solutions)
--
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-01 Thread Patrick Maupin
On Apr 1, 7:49 pm, Tim Chase python.l...@tim.thechases.com wrote:
 David Robinow wrote:
  $ python -c print 1/2 * 1/2
  0

   But that's not what I learned in grade school.
  (Maybe I should upgrade to 3.1?)

 That's because you need to promote one of them to a float so you
 get a floating-point result:

     1/2 * 1/2
    0
     1/2 * 1/2.0
    0.0

 Oh...wait ;-)

 -tkc

Hmmm, I think I'm starting to see why we need math.fsum() to take care
of those rounding errors...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-01 Thread Steven D'Aprano
On Thu, 01 Apr 2010 08:27:53 -0700, Den wrote about Python's ternary 
operator:

 I've been following this thread for a few days now.  My thoughts are
 that, in view of a long known widely used syntax for this operator,
 python's syntax seems like change for change sake.  If current
 programing paradigm provides that particular trinary operator, why
 should python's be different from the previously well known one.

Yes, I agree, we should be using the previously well known syntax:

condition - value_if_true, value_if_false

which was introduced by BCPL in 1966.


 For instance, no reasonable language designer would, now, use post-fix
 (I know about Forth) 

Do you also know about Postscript, Factor, Joy and Cat, to mention only a 
few? And also the native language of Hewlett-Packard scientific 
calculators, RPL.



 or allow only +=, -=, /=, etc. assignments ONLY.
 (Just as no reasonable car designer would put the accelerator pedal on
 the left.)  There are conventions which should span products.  Yes
 python has the trinary operator and it's not going to change, but this
 seems like a bit of petulance on the part of the designer.

Unless you have read the PEP that added the operator to the language, and 
the reasons for rejecting the alternatives, you are not qualified to 
guess what Guido's motives for choosing the current syntax are.

http://www.python.org/dev/peps/pep-0308/

You might not like it, but I do, and I like it far more than the ugly and 
hard to understand C syntax. In English (which has existed for much 
longer than C) the question mark punctuation symbol is a sentence 
terminator, not a separator between clauses, so using ? as an operator 
has always looked strange and disturbing to me.




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


Re: off topic but please forgive me me and answer

2010-04-01 Thread Steven D'Aprano
On Thu, 01 Apr 2010 19:55:27 -0400, David Robinow wrote:

 superpollo wrote:
  how much is one half times one half?
[...]
  Well, my python says:
 
 $ python -c print 1/2 * 1/2
 0
 
  But that's not what I learned in grade school.
 (Maybe I should upgrade to 3.1?)

Python 2.x defaults to integer division, a design error which has been 
rectified in 3.x.

One can do any of these:

[st...@sylar ~]$ python3.1 -c print(1/2 * 1/2)
0.25
[st...@sylar ~]$ python2.6 -c from __future__ import division; print 1/2 
* 1/2
0.25
[st...@sylar ~]$ python2.6 -Q new -c print 1/2 * 1/2
0.25
[st...@sylar ~]$ python2.6 -c print 0.5 * 0.5
0.25


and probably many others as well.



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


Re: off topic but please forgive me me and answer

2010-04-01 Thread Steven D'Aprano
On Thu, 01 Apr 2010 19:49:43 -0500, Tim Chase wrote:

 David Robinow wrote:
 $ python -c print 1/2 * 1/2
 0
 
  But that's not what I learned in grade school.
 (Maybe I should upgrade to 3.1?)
 
 That's because you need to promote one of them to a float so you get a
 floating-point result:
 
 1/2 * 1/2
0
 1/2 * 1/2.0
0.0
 
 Oh...wait ;-)

Tim, I'm sure you know the answer to this, but for the benefit of the 
Original Poster, the problem is that you need to promote *both* divisions 
to floating point. Otherwise one of them will give int 0, which gives 0.0 
when multiplied by 0.5.

 1.0/2 * 1/2.0
0.25


If you want an exact result when multiplying arbitrary fractions, you 
need to avoid floats and decimals and use Fractions:

 Fraction(1, 2)**2
Fraction(1, 4)



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


Re: off topic but please forgive me me and answer

2010-04-01 Thread Lie Ryan
On 04/02/10 13:01, Patrick Maupin wrote:
 On Apr 1, 7:49 pm, Tim Chase python.l...@tim.thechases.com wrote:
 David Robinow wrote:
 $ python -c print 1/2 * 1/2
 0

  But that's not what I learned in grade school.
 (Maybe I should upgrade to 3.1?)

 That's because you need to promote one of them to a float so you
 get a floating-point result:

 1/2 * 1/2
0
 1/2 * 1/2.0
0.0

 Oh...wait ;-)

 -tkc
 
 Hmmm, I think I'm starting to see why we need math.fsum() to take care
 of those rounding errors...

hmm?

 import math
 math.fsum([1/2, 1/2])
0.0

it doesn't appear to take care of those rounding errors, not in this
case at least.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Browser-based MMOG web framework

2010-04-01 Thread exarkun

On 01:14 am, srosbo...@gmail.com wrote:

Hi, I could use some advice on my project.

It's a browser-based MMOG: The High Seas (working title)

Basically it is a trading game set in 1600s or 1700s ... inspirations:
Patrician 3, Mine Things, Space Rangers 2, ...

Travel between cities takes several days: game updates trading ship
positions every 10 minutes.  Apart from that it handles player input
to buy/sell goods, if their ship is in port.

I want the game logic and world state data storage on a webserver,
with players connecting via web browser.  Also, I want to make an
admin mode client for me to keep track of the world and add changes
to game world stuff.

I want to use Python but I haven't ever used it in a web context.

http://wiki.python.org/moin/WebFrameworks lists several different
options for Python Web Frameworks: Django, Grok, Pylons, TurboGears,
web2py, Zope.  I've heard of Django and Grok...that's about my level
of knowledge here.

My question: can any of these frameworks help me with what I'm trying
to do?


This is something that Twisted and Nevow Athena will probably be really 
good at doing (a lot better than the ones you've mentioned above, I 
think).


You can find an Athena introduction here (at least for now, the content 
might move to another site before too long):


   http://divmodsphinx.funsize.net/nevow/chattutorial/

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


Re: off topic but please forgive me me and answer

2010-04-01 Thread Patrick Maupin
On Apr 1, 9:50 pm, Lie Ryan lie.1...@gmail.com wrote:
 On 04/02/10 13:01, Patrick Maupin wrote:



  On Apr 1, 7:49 pm, Tim Chase python.l...@tim.thechases.com wrote:
  David Robinow wrote:
  $ python -c print 1/2 * 1/2
  0

   But that's not what I learned in grade school.
  (Maybe I should upgrade to 3.1?)

  That's because you need to promote one of them to a float so you
  get a floating-point result:

      1/2 * 1/2
     0
      1/2 * 1/2.0
     0.0

  Oh...wait ;-)

  -tkc

  Hmmm, I think I'm starting to see why we need math.fsum() to take care
  of those rounding errors...

 hmm?

  import math
  math.fsum([1/2, 1/2])

 0.0

 it doesn't appear to take care of those rounding errors, not in this
 case at least.

you're right!  I mis-read the problem.  What we REALLY need is a good
math.fmul()   ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-01 Thread David Robinow
On Thu, Apr 1, 2010 at 10:44 PM, Steven D'Aprano
st...@remove-this-cybersource.com.au wrote:
 On Thu, 01 Apr 2010 19:49:43 -0500, Tim Chase wrote:

 David Robinow wrote:
 $ python -c print 1/2 * 1/2
 0

  But that's not what I learned in grade school.
 (Maybe I should upgrade to 3.1?)

 That's because you need to promote one of them to a float so you get a
 floating-point result:

     1/2 * 1/2
    0
     1/2 * 1/2.0
    0.0

 Oh...wait ;-)

 Tim, I'm sure you know the answer to this, but for the benefit of the
 Original Poster, the problem is that you need to promote *both* divisions
 to floating point. Otherwise one of them will give int 0, which gives 0.0
 when multiplied by 0.5.

 1.0/2 * 1/2.0
 0.25


 If you want an exact result when multiplying arbitrary fractions, you
 need to avoid floats and decimals and use Fractions:

 Fraction(1, 2)**2
 Fraction(1, 4)

I should have known he wouldn't get it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-01 Thread Tim Chase

Steven D'Aprano wrote:

That's because you need to promote one of them to a float so you get a
floating-point result:

1/2 * 1/2
   0
1/2 * 1/2.0
   0.0

Oh...wait ;-)


Tim, I'm sure you know the answer to this, but for the benefit of the 
Original Poster, the problem is that you need to promote *both* divisions 
to floating point. Otherwise one of them will give int 0, which gives 0.0 
when multiplied by 0.5.



1.0/2 * 1/2.0

0.25


You can get away with just promoting one of them...you just have 
to promote the _correct_ one (one involved in the first division) 
so that its promotion-of-subresult-to-float carries into all 
subsequent operations/operators:


   1/2 * 1/2 # (((1/2)*1)/2)==(((0)*1)/2) in 2.x
  0
   1/2 * 1/2.0 # (((1/2)*1)/2.0)==(((0)*1)/2.0) in 2.x
  0.0
   1/2 * 1.0/2 # (((1/2)*1.0)/2)==(((0)*1.0)/2) in 2.x
  0.0
   1/2.0 * 1/2 # (((1/2.0)*1)/2)
  0.25
   1.0/2 * 1/2 # (((1.0/2)*1)/2)
  0.25

I'd rather be explicit in *real* code that I'd write and 
explicitly float'ify constants or float() integer variables. The 
OP's question was both OT and pretty basic middle-school math 
that google would have nicely answered[1] so IMHO warranted a bit 
of fun. :)


-tkc

[1]
http://www.google.com/search?q=1%2F2+*+1%2F2



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


Re: C-style static variables in Python?

2010-04-01 Thread Paul Rubin
kj no.em...@please.post writes:
 When coding C I have often found static local variables useful for
 doing once-only run-time initializations.  For example:

 int foo(int x, int y, int z) {
   static int first_time = TRUE;
   static Mongo *mongo;
   if (first_time) { ...


Here are some cheesy ways.

1. Put an attribute onto the function name:

  def foo(x, y, z):
if foo.first_time:
   foo.mongo = heavy_lifting_at_runtime()
   foo.first_time = False
...
  foo.first_time = True

2. Use a mutable keyword parameter:

   def foo(x, y, z, wrapped_mongo=[]):
  if len(wrapped_mongo) == 0:
 wrapped_mongo.append(heavy_lifting_at_runtime())
  mongo = wrapped_mongo[0]
  ...

3. Streamline the first method a little:

def foo(x, y, z):
   if len(foo.wrapped_mongo == 0):
  foo.wrapped_mongo.append(heavy_lifting_at_runtime())
   mongo = foo.wrapped_mongo[0]  
   ...
   foo.wrapped_mongo = []

All of these of course don't give as good encapsulation as one might
like.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good Intermediate Tutorials

2010-04-01 Thread Lie Ryan
On 04/02/10 11:25, Abethebabe wrote:
 I've recently finished reading A Byte Of Python and have the basics of
 Python down. I want to continue practice but I'm unsure what I can do.
 So I started looking for tutorials to open my mind a little, but
 everything I come across are beginner tutorials that cover the same
 topics...over and over.

In programming, if you've gone past the beginner level, the only text
you ever need is the reference manual.

If you want to broaden your mind, you may want to learn other languages
that have distinctly different paradigms than the ones you already know.
Then when you get back to python, you will be able to see new angles to
attack a problem from.

 Can anyone point me to good Intermediate tutorials, that don't make
 use of libraries and such (so I can get really comfortable with the
 core language.) Maybe even the source code of some simple Python
 applications, so I can observe and learn the code myself.
 
 Really appreciative of any help!

Strengthen your math, specifically discrete math; many problems are just
different manifestations of a few classes of problem. You can leverage
developing completely new methods and new ideas by abstracting your
problem to find out the the class of problem your problem belongs to.
(contrived analogy: a head chef need to determine whether the remaining
ingredients will suffice for the day; a bricklayer need to determine the
number of bricks he need to buy for a span of wall; those problems has a
common solution: counting and number division).

In short, read a book about math and/or problem solving.
Recommendations: The Art of Computer Programming by D.E. Knuth,
Algorithm Design Manual by S.S. Skiena.

Frequent the mailing list. Only by then you will learn to write
idiomatic python; a book can be compiled about common python idioms
but they will more-or-less be the author's perspective of the idioms
instead of actual python's idioms. I found that, in python at least,
avoiding use of library often forces you to write non-idiomatic python
because many libraries are written specifically because it is difficult
to write the equivalent efficient code with idiomatic python.

In short, don't avoid the library if you want to learn idiomatic python.
(if you want to learn about the algorithms though, avoiding libraries is
a fine restriction)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-01 Thread Steve Howell
On Mar 30, 8:40 am, gentlestone tibor.b...@hotmail.com wrote:
 Hi, how can I write the popular C/JAVA syntax in Python?

 Java example:
     return (a==b) ? 'Yes' : 'No'

 ;  first idea is:
     return ('No','Yes')[bool(a==b)]

 Is there a more elegant/common python expression for this?

The ironic thing about the ternary operator is that it is not really
ternary; it's binary.  Even just making an expression from a binary
operator inevitably leads to syntax hell.

There is a principle of programming that I would like to coin, which
is the Tyranny of Three.

It is impossible to code for any expression that has three possible
values in any kind of elegant way.  It's just impossible.  Try to code
the bowling game without tearing out your teeth--three conditions:
strike, spare, or normal.

The tyranny of three is that 3 is too small for an elegant N-based
solution and too large for a simple condition.

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


Re: Good Intermediate Tutorials

2010-04-01 Thread Ray Allen
In my opinion, the python official documents, include the tutorial, language
reference, library reference, distributing python modules, also extending
and embedding, Python/C API, are all what you need to learn python and use
it, as long as you can read into it. Also you can read other python
programs. If you want to know more you can read the cpython source itself.
Its not too difficult.



-- 
Ray Allen
Best wishes!
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >