Re: Three days with some of the coolest people in ruby and rails

2008-10-07 Thread Chris Rebert
Not that I particularly have anything against Ruby or Rails, but your
post isn't quite germane to this mailinglist, which is about Python,
not Ruby.
Though they are similar languages, your post is entirely devoid of
even any reference to Python and thus is not at all relevant.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Tue, Oct 7, 2008 at 9:47 PM, hjk1127 [EMAIL PROTECTED] wrote:
 What could be cooler than Ruby and Rails authors, experts, and
 hundreds of professionals that work with Ruby on a daily basis – all
 together in one location for great discussions and debates? That's
 what will happen at the Voices That Matter: Professional Ruby
 Conference coming to Boston, November 18-20th.

 Obie Fernandez - Giles Bowkett – Josh Susser - Blaine Cook - Ezra
 Zygmuntowicz - Michael Hartl - Thomas Enebo - Hal Fulton - and dozens
 of others!

 You should join us! We'll be talking about some intriguing topics and
 there will be lots of time for QA and code sharing. It'll be
 educational and it'll be fun.

 Give us a call or send us an email now and we'll tell you all about
 the event and provide you with a free eBook.

 To request more information and receive your free eBook, email
 [EMAIL PROTECTED], call 617-848-7026, or request information
 online at http://www.voicesthatmatter.com/ruby2008/index.aspx.

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

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


Re: Job Posting

2008-10-08 Thread Chris Rebert
On Wed, Oct 8, 2008 at 9:20 AM, Capuano, Rebecca
[EMAIL PROTECTED] wrote:
 HI,

 Would you be able to post this on your site? I don't know if you post jobs.
 Thanks!

This is a general-interest mailinglist about the Python programming
language, not a way of directly contacting just the Python.org admins.
Based on the Community -- Jobs page from the python.org website, you
can find instructions on submitting a job posting on
http://www.python.org/community/jobs/howto/

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Our client in Princeton, NJ is looking for a Python Developer to join its
 team.

 Description
 A small to medium Python project needs a motivated developer to work with
 the team lead.  The position entails designing, implementing, and  testing a
 flexible schema definition and data cataloging front end for an image and
 metadata management system.  The project may include  building a distributed
 image repository system as well as the cataloging tool.  The entire project
 will eventually be released as  open source software.

 6-month+ project.

 Requirements

 3+ years of Python experience preferably in a professional capacity.
 Familiarity with JQuery, PIL, SQLAlchemy, PyProcessing, Pylons, Django.
 Knowledge of functional programming is a plus.
 Knowledge of image processing is a plus.
 Excellent verbal and written communication skills.

 You will be required to write some python code as part of  the interview
 proces

 To apply please contact:
 Rebecca Capuano
 Sr. Recruiter
 Information Technology and Engineering
 TECHNISOURCE
 100 Wood Ave. South, Suite 208, Iselin, New Jersey 08830
 Direct 732.635.0700 x 227 | fax 800.258.9775
 [EMAIL PROTECTED] | www.technisource.com

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


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


Re: Inefficient summing

2008-10-08 Thread Chris Rebert
I personally would probably do:

from collections import defaultdict

label2sum = defaultdict(lambda: 0)
for r in rec:
for key, value in r.iteritems():
label2sum[key] += value

ratio = label2sum[F1] / label2sum[F2]

This iterates through each 'r' only once, and (imho) is pretty
readable provided you know how defaultdicts work. Not everything has
to unnecessarily be made a one-liner. Coding is about readability
first, optimization second. And optimized code should not be
abbreviated, which would make it even harder to understand.

I probably would have gone with your second solution if performance
was no object.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Wed, Oct 8, 2008 at 1:23 PM, beginner [EMAIL PROTECTED] wrote:
 Hi All,

 I have a list of records like below:

 rec=[{F1:1, F2:2}, {F1:3, F2:4} ]

 Now I want to write code to find out the ratio of the sums of the two
 fields.

 One thing I can do is:

 sum(r[F1] for r in rec)/sum(r[F2] for r in rec)

 But this is slow because I have to iterate through the list twice.
 Also, in the case where rec is an iterator, it does not work.

 I can also do this:

 sum1, sum2= reduce(lambda x, y: (x[0]+y[0], x[1]+y[1]), ((r[F1],
 r[F2]) for r in rec))
 sum1/sum2

 This loops through the list only once, and is probably more efficient,
 but it is less readable.

 I can of course use an old-fashioned loop. This is more readable, but
 also more verbose.

 What is the best way, I wonder?


 -a new python programmer
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: A question about funcation parameter and self defined object

2008-10-08 Thread Chris Rebert
On Wed, Oct 8, 2008 at 4:36 PM, Wei Guo [EMAIL PROTECTED] wrote:
 Hi,

 I defined a class called vec3 which contains x, y, z and in another
 function, I tried to call a function which takes a vec3 as a parameter, but
 it seems that parameter is passed as a generic object and I can not access x
 , y, z in my vec3. Could anyone help me with that?

Being dynamically typed, Python has no notion of variables having
types, so the object isn't being passed as a generic object, you're
getting what really is a generic object value of type NoneType,
which means the value of traV is indeed None, not vec3().


 class vec3:
 def __init__(self, x_ = 0.0, y_ = 0.0, z_ = 0.0):
 self.x = x_
 self.y = y_
 self.z = z_
 class mat4:
  def translation( traV = vec3() ):
   tranM.rowLst[index][0] = traV.x
 AttributeError: 'NoneType' object has no attribute 'x'

This code is perfectly fine. See below.


 Could anyone help me how to turn the traV as type of vec3() instead of
 NoneType object?

That's not what's happening. It's not like traV is being cast to
NoneType thus making x inaccessible, as that's not even possible to
express in Python.
What's happening is something is calling translation() with None as an
argument, and of course None (the value the caller provided for traV)
has no attribute 'x', hence the error. So, check the full exception
traceback and see who's calling translation() and how the argument
being passed to it got to be None.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks a lot,

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


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


Re: Safe eval of insecure strings containing Python data structures?

2008-10-08 Thread Chris Rebert
On Wed, Oct 8, 2008 at 5:34 PM, Warren DeLano [EMAIL PROTECTED] wrote:

 I would like to parse arbitrary insecure text string containing nested
 Python data structures in eval-compatible form:

 # For example, given a config.txt such as:

 {
  'my_atom' : 1.20,
  'my_dict' : { 2:50 , 'hi':'mom'},
  'my_list' : [ (1,2,3), [4.5,6.9], 'foo', 0 ]
 }

 # I would like to do something like this:

 empty_space = {'__builtins__' : {}}

 try:
config = eval(open(config.txt).read(), empty_space, empty_space)
 except:
config = {}

 print config

 # But I know for certain that the above approach is NOT secure since
 object attributes can still be accessed...

 So is there an equally convenient yet secure alternative available for
 parsing strings containing Python data structure definitions?

Assuming the data structures are sufficiently basic, i.e. no class
instanciations, you can just use the json (AKA simplejson) library to
deserialize the data in the string. Python and JSON conveniently
happen to share the same syntax for literals (except for booleans
IIRC).
Also, if this is your program's config file, you might consider
changing it to INI-format and using ConfigParser
(http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html)
instead.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks in advance for any pointers!

 Cheers,
 Warren


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

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


Re: default value in __init__

2008-10-09 Thread Chris Rebert
See Pitfall #5 on http://zephyrfalcon.org/labs/python_pitfalls.html
It also applies to dictionaries (and sets, any mutable object really).

On Thu, Oct 9, 2008 at 1:03 AM, kenneth [EMAIL PROTECTED] wrote:
 Dear all,

 I have encountered this weird problem.

 I have a class definition with an __init__ argument 'd'
 which defaults to {}. This argument is put in the 'self.d'
 attribute at initialization

 I create two independent instances of this class; the code
 is as follows.

 class C:
  def __init__(self, i=10, d = {}):

Change 'd = {}' to 'd=None'
Add the line:
if d is None: d = {}

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

self.d = d
self.i = i
  def get(self):
print
print self.d
  def set(self, dval, ival):
self.d.update(dval)
self.i+=ival

 c1=C()
 c1.set({'one':1},3)
 c1.get()

 del c1

 c2=C()
 c2.set({'two':2},4)
 c2.get()


 If I run the code I obtain:

 {'one': 1}

 {'two': 2, 'one': 1}

 It seems that the 'self.d' argument of the second instance is the
 same of the 'self.d' of the first (deleted!) instance.

 Running the code in a debugger I discovered that, when I enter the
 __init__ at the second initialization, before doing

 self.d = d

 the 'd' variable already contains the 'self.d' value of the first
 instance and not the default argument {}.

 Am I doing some stupid error, or this is a problem ?

 Thanks in advance for any help,
 Paolo
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: default value in __init__

2008-10-09 Thread Chris Rebert
On Thu, Oct 9, 2008 at 1:39 AM, kenneth [EMAIL PROTECTED] wrote:
 On Oct 9, 10:14 am, Christian Heimes [EMAIL PROTECTED] wrote:
 kenneth wrote:
  the 'd' variable already contains the 'self.d' value of the first
  instance and not the default argument {}.

  Am I doing some stupid error, or this is a problem ?

 No, it always contains the default argument because default values are
 created just ONE 
 TIME.http://effbot.org/pyfaq/why-are-default-values-shared-between-objects...


 Wow, it's a very dangerous behavior ...

 Just to know, is this written somewhere in the python documentation or
 one has to discover it when his programs fails to work ;-) ?

It's mentioned in the tutorial (note the Important warning):
http://docs.python.org/tutorial/controlflow.html#default-argument-values

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: How to do regular BASH work in Python?

2008-10-09 Thread Chris Rebert
You might also be interested in the 'shutil' module:
http://docs.python.org/library/shutil.html#module-shutil

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Thu, Oct 9, 2008 at 7:13 AM, Frantisek Malina [EMAIL PROTECTED] wrote:
 Hey,
 I found it. Python rocks:
 http://www.python.org/doc/2.5.2/lib/os-file-dir.html

 If you have any further links that provide some lively code examples
 and recipes, please pass them on.

 Thank you

 Frank Malina
 http://vizualbod.com
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Total Python Noob

2008-10-10 Thread Chris Rebert
On Thu, Oct 9, 2008 at 11:22 PM, Tom Lake [EMAIL PROTECTED] wrote:
 I have Python 2.6 installed on Vista Ultimate.  When I try to calculate
 sqrt (or any transcendental functions) I get the following error

 sqrt(2)

 Traceback (most recent call last):
  File stdin, line 1, in module
 NameError: name 'sqrt' is not defined

 What am I doing wrong?

They're not buitltin, they're in the 'math' module
(http://docs.python.org/library/math.html#module-math), which you need
to import.
e.g.
import math
print math.sqrt(4)

Please also Read the Fine Tutorial at:
http://docs.python.org/tutorial/index.html

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: default value in __init__

2008-10-10 Thread Chris Rebert
On Fri, Oct 10, 2008 at 4:36 AM,  [EMAIL PROTECTED] wrote:
 Bruno Desthuilliers:
 You mean : to people that don't bother reading the FineManual *nor*
 searching the newsgroup / ML archives ?

 Are there ways to change how Python3 manages arguments and functions,
 to remove this antifeature of Python, avoiding this common mistake
 done by every newbie?
 I don't care if it reduces the performance of Python a little.

The general idea been discussed ad-nauseum on the list several times
before, including just 2 months ago. See e.g.:

[Python-3000] default argument surprises
http://mail.python.org/pipermail/python-3000/2008-August/014658.html

[Python-ideas] proto-PEP: Fixing Non-constant Default Arguments
http://mail.python.org/pipermail/python-ideas/2007-January/000121.html

[Python-3000] pre-PEP: Default Argument Expressions
http://mail.python.org/pipermail/python-3000/2007-February/005704.html

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Bye,
 bearophile
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Unicode equality from raw_input

2008-10-11 Thread Chris Rebert
In order to convert a byte sequence to Unicode, Python needs to know
the encoding being used. When you don't specify a encoding, it tries
ASCII, which obviously errors if your byte sequence isn't ASCII, like
in your case.

Figure out what encoding your terminal/system is set to, then use the
.decode() method to change the bytes to a unicode object. E.g.:

bytestring = raw_input(text: )
as_unicode = bytestring.decode('utf8') #assuming the encoding is UTF-8
print as_unicode == uおはよう #== True

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


2008/10/11 Damian Johnson [EMAIL PROTECTED]:
 Hi, when getting text via the raw_input method it's always a string (even if
 it contains non-ASCII characters). The problem lies in that whenever I try
 to check equality against a Unicode string it fails. I've tried using the
 unicode method to 'cast' the string to the Unicode type but this throws an
 exception:

 a = raw_input(text: )
 text: おはよう
 b = uおはよう
 a == b
 __main__:1: UnicodeWarning: Unicode equal comparison failed to convert both
 arguments to Unicode - interpreting them as being unequal
 False
 type(a)
 type 'str'
 type(b)
 type 'unicode'
 unicode(a)
 Traceback (most recent call last):
   File stdin, line 1, in module
 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0:
 ordinal not in range(128)
 str(b)
 Traceback (most recent call last):
   File stdin, line 1, in module
 UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3:
 ordinal not in range(128)


 After a couple hours of hair pulling I think it's about time to admit
 defeat. Any help would be appreciated! -Damian


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


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


Re: Decrease code redundancy without breaking references

2008-10-11 Thread Chris Rebert
for cfg in settings_modules:
cfg.TEMPLATE_DIRS = (/clients/+ cfg.SITE_FOLDER+/templates,
/packages/apps/templates)
cfg.MEDIA_FILES_PREFIX = 'http://'+ cfg.SITE_DOMAIN+'/media/'
cfg.VIDEO_FILES_URL = 'http://'+ cfg.SITE_DOMAIN+'/video/'
cfg.VIDEO_FILES_ROOT = '/clients/'+ cfg.SITE_FOLDER+'/video'


Without more information about how your code is structured, it's hard
to give more precise advice.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


On Sat, Oct 11, 2008 at 7:28 PM,  [EMAIL PROTECTED] wrote:
 My settings file
 ---
 from global_settings import *

 SITE_FOLDER   = 'mypipe'
 SITE_DOMAIN   = 'localhost'
 SITE_NAME = 'My Pipe'
 SITE_ID   = 1

 TEMPLATE_DIRS = (/clients/+SITE_FOLDER+/templates, /packages/apps/
 templates)
 MEDIA_FILES_PREFIX = 'http://'+SITE_DOMAIN+'/media/'
 VIDEO_FILES_URL = 'http://'+SITE_DOMAIN+'/video/'
 VIDEO_FILES_ROOT = '/clients/'+SITE_FOLDER+'/video'
 __

 The  first 4 settings are unique to every setting file.

 The last 4 lines (TEMPLATE_DIRS - MEDIA_ROOT) are always based on the
 SITE_FOLDER  and SITE_DOMAIN and are the same in all my config files.

 How can I separate the last 4 lines repetitive lines (I need to DRY
 the code)?

 Frank
 http://vizualbod.com
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Question

2008-10-13 Thread Chris Rebert
To be a bit less sarcastic than the other replies, your question is
*much* *much* too vague to be answered.
Unless you give us more specific information and ask a more precise
question, it's impossible help you.
See the link someone already replied with for some good advice on how
to do that.

Also, please don't double-post like you just did, as that's bad
netiquette and just wastes everyone's time.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Mon, Oct 13, 2008 at 7:15 AM, Aditi Meher [EMAIL PROTECTED] wrote:
 Hello

 How to write code to store data into buffer using python?

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

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


Re: How to set cookie in client machine

2008-10-13 Thread Chris Rebert
See the 'cookie' module: http://www.python.org/doc/2.5.2/lib/module-Cookie.html

Also:
A. In the future, Google is your friend! That page is the top hit for
python cookie for Christ's sake; it's not hard to find.
B. Please don't post your question again just because it isn't
answered fast enough. You didn't even wait one whole day before
reposting.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Mon, Oct 13, 2008 at 10:39 PM, Good Z [EMAIL PROTECTED] wrote:
 Hello,

 I want to set {name, value} cookie on client machine.

 My requirement is that when user comes to the website hosted on our server
 and login into his account, we would like to set user specific information
 in cookie (on his machine) that will be used later when HTTP request comes
 in. Is there a generic program that may help me out in setting the cookie on
 client machine?

 I will not be able to use HttpResponse and set cookie in it since within the
 program i need to redirect it to different URL.

 Regards,
 Mike



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


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


Re: IDE Question

2008-10-15 Thread Chris Rebert
You can find a list and several reviews on
http://wiki.python.org/moin/IntegratedDevelopmentEnvironments
I think Wing IDE (http://www.wingware.com/products) is generally
thought to be the most sophisticated one; but it's neither open-source
nor gratis (they do let noncommerical open-source devs get a free copy
though).
From what I've heard anecdotally, most Pythonistas don't use IDEs,
instead opting for just a text editor (often vim or emacs). So the
answer to your question is probably None.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Wed, Oct 15, 2008 at 10:19 AM, Steve Phillips [EMAIL PROTECTED] wrote:
 Hi All,
 I am just wondering what seems to be the most popular IDE. The reason
 I ask is I am currently at war with myself when it comes to IDE's. It
 seems like every one I find and try out has something in it that
 others don't and viceversa. I am in search for the perfect IDE and
 after many months of searching, I always come back to IDLE to do what
 I need to do. I want to use Komodo badly but the one issue I have with
 that is sometimes the auto-complete works and other times it doesn't.
 Even if I carbon copy a script.

 Thanks in advance,
 Steve P
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: PDF warning under Ubuntu and Fedora

2008-10-15 Thread Chris Rebert
CUPS is the Common Unix Printing System. See
http://en.wikipedia.org/wiki/CUPS for more info.
Apparently something (your script or one of the libraries it uses
perhaps?) is trying to create a new printer called PDF and failing
because that name is already in use, hence the warnings.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Wed, Oct 15, 2008 at 1:21 PM, Stef Mientki [EMAIL PROTECTED] wrote:
 hello,

 Does anyone recognize this warning, which is produced under Ubuntu and
 Fedora but not under Windows ?

 ** (python:10896): WARNING **: Can't create printer PDF because the id
 PDF is already used (python:10896): GnomePrintCupsPlugin-WARNING **: The
 CUPS printer PDF could not be created
 (python:10896): GnomePrintCupsPlugin-WARNING **: The data for the CUPS
 printer PDF could not be loaded.

 thanks,
 Stef Mientki
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: PDF warning under Ubuntu and Fedora

2008-10-15 Thread Chris Rebert
On Wed, Oct 15, 2008 at 2:12 PM, Stef Mientki [EMAIL PROTECTED] wrote:
 Chris Rebert wrote:

 CUPS is the Common Unix Printing System. See
 http://en.wikipedia.org/wiki/CUPS for more info.
 Apparently something (your script or one of the libraries it uses
 perhaps?) is trying to create a new printer called PDF and failing
 because that name is already in use, hence the warnings.


 Thanks Chris,
 it must one of the (standard) Python libraries I use.
 Although it's not a big issue,
 is there a simple solution to prevent this warning ?

You'd probably have to ask on a GNOME developer mailinglist as
GnomePrintCupsPlugin appears to be the culprit.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 cheers,
 Stef

 Cheers,
 Chris


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

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


Re: default value in __init__

2008-10-16 Thread Chris Rebert
On Wed, Oct 15, 2008 at 9:43 PM, Aaron Castironpi Brady
[EMAIL PROTECTED] wrote:
 On Oct 15, 11:33 pm, Steve Holden [EMAIL PROTECTED] wrote:
 Aaron Castironpi Brady wrote:

 [about how default argument behavior should, in his opinion, be changed]

 Say what you like. The language is as it is by choice. Were it, for some
 reason, to change we would then be receiving posts every week that
 didn't understand the *new* behavior.

 Sometimes people just have to learn to confirm with reality instead of
 requiring reality to confirm with their preconceptions. This is one such
 case.

 regards
  Steve
 --
 Steve Holden+1 571 484 6266   +1 800 494 3119
 Holden Web LLC  http://www.holdenweb.com/

 I am not convinced it should either stay or go, but it's hard to argue
 one way or the other about something so deeply entrenched.  However,
 what are your thoughts, whatever the default behavior is, on a
 decorator that provides the alternative?  That is, a decorator that
 either reevaluates default arguments each time when the language
 evaluates them once, or a decorator that evaluates arguments once,
 when the languages evaluates them each time?

 P.S.
 we would then be receiving posts every week that
 didn't understand the *new* behavior.
 That is not obvious and I don't know of any empirical evidence that
 entails it.  Hard to search the standard library for that figure.

Although primitive and likely somewhat flawed, you may find the
statistics in the Compatibility Issues section of
http://mail.python.org/pipermail/python-3000/2007-February/005704.html
to be of interest.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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

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


Re: account balance checker

2008-10-16 Thread Chris Rebert
You'd probably have to use something like mechanize
(http://wwwsearch.sourceforge.net/mechanize/) to fill out the forms,
but if BofA's website uses Javascript at all, you're probably out of
luck.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Wed, Oct 15, 2008 at 8:09 AM, Support Desk
[EMAIL PROTECTED] wrote:
 Hello all,

I was wondering if it would be possible to make a script to grab my
 balance account balance a few times a day without having to login every
 time. I know I can use the urlib2 library, but not sure how to go about
 filling in the forms and submitting them. BOA has a mobile site that is
 pretty simple.  Anyone else use Bank of America and would be interested in
 this. This is not for anything illegal, just for me to prevent overdrafting
 my account

 https://sitekey.bankofamerica.com/sas/signonScreen.do?isMobileDevice=true



 y =
 urllib.urlopen('https://sitekey.bankofamerica.com/sas/signonScreen.do?isMobl
 eDevice=true',urllib.urlencode({'onlineID':'MYONLLINEID'})).readlines()

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

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


Re: Dictionary of Dicts question

2008-10-16 Thread Chris Rebert
On Thu, Oct 16, 2008 at 12:19 PM, John Townsend [EMAIL PROTECTED] wrote:
 I'm working with a Dictionary of Dicts. Something like this:

 myDict = {
 'TestName': {
 'FileName':{

 'ct_init':1234,

 'psl_init':5678,

 'total_test_time':7890,

 'psl_shutdown':8765,

 'ct_shutdown':9021,

 'total_time':3421,
 },
 }
 }

 Accessing values is pretty straightforward (nice change from my Perl days).
 For example:

 myDict['TestName']['FileName']['ct_shutdown']

 in Python interpreter yields

 9021

 However, when I try to add, let's say, a new FileName entry, I end up
 replacing the previous FileName entry.

 In Python interpreter, I try:

 myDict['TestName'] = {'NewFileName': {}, }

 I get

 {'TestName': {'NewFileName': {}}}

Right, this clobbers the existing entry with this new blank one. This
is evidenced by the fact that you're performing an _assignment_ on a
dictionary key rather than calling a _mutator_ method on a dictionary
value. A dictionary has only one value for a given key (but
importantly, that value can be a list).


 So, how do I add a new entry without replacing the old entry?

Switch to a Dict of Lists of Dicts and append to the appropriate list
when adding the new entry, or preferably, start using objects instead
of ad-hoc nested dictionaries.

Regards,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks

 John Townsend (5-7204),
 AGM-FL and PSL QE Lead



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


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


Re: Unicode File Names

2008-10-16 Thread Chris Rebert
2008/10/16 Jordan [EMAIL PROTECTED]:
 On Oct 16, 9:20 pm, John Machin [EMAIL PROTECTED] wrote:
 On Oct 17, 11:43 am, Jordan [EMAIL PROTECTED] wrote:

  I've got a bunch of files with Japanese characters in their names and
  os.listdir() replaces those characters with ?'s. I'm trying to open
  the files several steps later, and obviously Python isn't going to
  find '01-.jpg' (formally '01-ひらがな.jpg') because it doesn't exist.
  I'm not sure where in the process I'm able to stop that from
  happening. Thanks.

 The Fine Manual says:
 
 listdir( path)

 Return a list containing the names of the entries in the directory.
 The list is in arbitrary order. It does not include the special
 entries '.' and '..' even if they are present in the directory.
 Availability: Macintosh, Unix, Windows.
 Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a
 Unicode object, the result will be a list of Unicode objects.
 

 Are you unsure whether your version of Python is 2.3 or later?

 *** Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32
 bit (Intel)] on win32. *** says my interpreter

 when it says if path is a Unicode object..., does that mean the path
 name must have a Unicode char?

No, it means if path is of type 'unicode' as opposed to type 'str'.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: properties access by name

2008-10-17 Thread Chris Rebert
Since rwproperty appears to use descriptors just like regular
property(), you'd do it the same way as for any normal attribute,
namely:

#for reading
print foo.y
#is the same as
print getattr(foo, y)

#for writing
foo.x = 1
#is the same as
setattr(foo, x, 1)


Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Fri, Oct 17, 2008 at 9:36 AM, Митя [EMAIL PROTECTED] wrote:
 I use rwproperty (http://pypi.python.org/pypi/rwproperty/1.0) and so I
 have properties in my class. Also I have a list of names of properties
 wich I am to set. How can I access my properties by name in such way
 that when I want to set a property, setter will be called, and and
 when I want to read it - getter?

 I have something like this:

 class Film(object):
def __init__(self, title):
self.__title = title

@getproperty
def title(self):
return self.__title
@setproperty
def title(self, value):
self.__title = value

 properties_to_set = ['title']
 f = Film('aaa')

 I d want to have sth like:
 f(properties_to_set[0]) = 'bbb'

 If title was a simple variable I could write:
 f.__dict__[properties_to_set[0]] = 'bbb'

 now I can write:
 f.__dict__['_Film__' + properties_to_set[0]] = 'bbb'

 but I want to set my property through the provided setter. How can I
 do this?

 P.S. Sorry for my english
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Normalizing arguments

2008-10-17 Thread Chris Rebert
On Fri, Oct 17, 2008 at 8:37 AM, Dan Ellis [EMAIL PROTECTED] wrote:
 Given some function, f(a, b, c=3), what would be the best way to go
 about writing a function, g(f, *args, **kwargs), that would return a
 normalized tuple of arguments that f would receive when calling
 f(*args, **kwargs)? By normalized, I mean that the result would always
 be (a, b, c) regardless of how g was called, taking into account
 positional arguments, keyword arguments, and f's default arguments.

 g(f, 1, 2, 3) - (1, 2, 3)
 g(f, 1, 2, c=3) - (1, 2, 3)
 g(f, 1, c=3, b=2) - (1, 2, 3)
 g(c=3, a=1, b=2) - (1, 2, 3)
 g(1, 2) - (1, 2, 3)

 All the required information is available between args, kwargs and f
 (the function object), but I don't know the exact algorithm. Has
 anyone already done this, or should I just dig around in the CPython
 source and extract an algorithm from there?
 --
 http://mail.python.org/mailman/listinfo/python-list


Why do you want/need this magical g() function considering that, as
you yourself point out, Python already performs this normalization for
you?

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Script can't find input file despite being in the same directory

2008-10-17 Thread Chris Rebert
On Fri, Oct 17, 2008 at 10:07 AM, Robocop [EMAIL PROTECTED] wrote:
 I have a simple little script that reads in postscript code, appends
 it, then writes it to a new postscript file.  Everything worked fine a
 month ago, but after rearranging my directory tree a bit my script
 fails to find the base postscript file.

 The line in question is:

  for line in fileinput.input(['base.ps']):
output.write(line)

What directory is output if you insert the lines:

from os import getcwd
print CWD:, getcwd()

just before the line is question?

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 I'm kind of at a loss as the script is executing in the same directory
 as base.ps, yet it can't find it.  I'm relatively new to python
 scripting, so i'm expecting it's just something i haven't learned
 about python that is causing the problem.  Any suggestions would be
 greatly appreciated.
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Log Exception with Backtrace

2008-10-17 Thread Chris Rebert
On Fri, Oct 17, 2008 at 9:40 AM, Heston James - Cold Beans
[EMAIL PROTECTED] wrote:
 Afternoon Guys,

 I'm currently logging exceptions within my applications like so:

 try:
 #do something
 except Exception, error:
 # Log the exception.
 self.logger.error(Exception Occurred: (%s) % str(error))


 This is quite fine, however, sometimes I get very vague error message thrown
 at me which don't help a great deal. How can I log the full exception and
 backtrace as if it were thrown to stderr and I wasn't catching it?

Use format_exc() in the 'traceback' module to get a string for the
current stack trace (and exception) and log that.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Cheers all,
 Heston

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

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


Re: algorizm to merge nodes

2008-10-17 Thread Chris Rebert
(Disclaimer: completely untested)

from collections import defaultdict

merged = defaultdict(list)
for key, val in your_list_of_pairs:
merged[key].append(val)

result = [[key]+vals for key, vals in merged.items()]

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Fri, Oct 17, 2008 at 1:20 PM, JD [EMAIL PROTECTED] wrote:
 Hi,

 I need help for a task looks very simple:

 I got a python list like:

 [['a', 'b'], ['c', 'd'], ['e', 'f'], ['a', 'g'], ['e', 'k'], ['c',
 'u'], ['b', 'p']]

 Each item in the list need to be merged.

 For example, 'a', 'b' will be merged, 'c', 'd' will be merged.

 Also if the node in the list share the same name, all these nodes need
 be merged.

 For example, ['a', 'b'], ['a', 'g'] ['b', 'p'] will be merged to ['a',
 'b', 'g', 'p']

 The answer should be:

 [['a', 'b', 'g', 'p'], ['c', 'd', 'u'], ['e', 'f', 'k']]

 Anyone has a solution?

 Thanks,

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

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


Re: better scheduler with correct sleep times

2008-10-18 Thread Chris Rebert
On Sat, Oct 18, 2008 at 5:09 AM, qvx [EMAIL PROTECTED] wrote:
 I need a scheduler which can delay execution of a
 function for certain period of time.
 My attempt was something like this:

[code snipped]

 But then I came up with the following case:

 1. I call delay with delay_sec = 10
 2. The scheduler goes to sleep for 10 seconds
 3. In the meantime (lets say 1 second later) I delay
   another func but this time with delay_sec=0.5
 4. The scheduler is sleeping and won't know call my
   second function for another 9 seconds insted of 0.5

 I started googling for scheduler and found one in standard library
 but ih has the same code as mine (it calls the  functions in the
 right order and my doesn't, but it still waits too long).
 The other schedulers from web are dealing with
 repeating tasks and such.

 So, I wrote this:

[more code snipped]

 Is there a better way or some library that does that?

I believe you're looking for the 'sched' module:
http://www.python.org/doc/2.5.2/lib/module-sched.html

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 My observations:

 1. Threading module uses time.sleep instead of time.clock
   which results in less precise results (on windows platform)

if sys.platform==win32:  #take care of differences in clock
 accuracy
wallclock = time.clock
else:
wallclock = time.time

 2. while analyzing threading module i noticed that wait() is
   implemented via loop and tiny sleep periods. I was expecting
   the usage of underlaying OS primitives and functions but
   then I remembered about GIL and quasi-multithreaded nature
   of Python. But still, isn't there a more precise method
   that interpreter itself could implement?

 Thanks,
 Tvrtko

 P.S. This was Python 2.5
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: default value in __init__

2008-10-19 Thread Chris Rebert
On Sun, Oct 19, 2008 at 12:56 AM, Paul McGuire [EMAIL PROTECTED] wrote:
 On Oct 14, 1:36 pm, David C. Ullrich [EMAIL PROTECTED] wrote:
  Well... How to say.. Is there any chance these people will read anything
  *at all* ?

 No. That's exactly the point! Basic Python is so transparent that
 you can start using it without reading anything, just looking at
 a few examples. _Because_ of that it's their responsibility to
 ensure that if you look at a few examples you then have a complete
 understanding of the language.

 I agree, Python really does strive to be intuitive and easy-to-learn.
 So the oddity of the behavior of optional_list_arg=[] is a recurring
 surprise to those who jump first and read documentation later.
 Besides the tutorials, reference docs, and FAQs, there are also some
 web pages with titles like Python Gotchas and Common Mistakes in
 Python that usually tread this ground too.

Specifically:
http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html?page=2
http://www.ferg.org/projects/python_gotchas.html#contents_item_6
http://zephyrfalcon.org/labs/python_pitfalls.html

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 In particular default parameters should work the way the user
 expects! The fact that different users will expect different
 things here is no excuse...

 Are you being sarcastic?  Short of import mindreading, I don't know
 how Python would know which behavior a given user would expect.  Maybe
 instead of a code smell, this particular Python wart is a design
 smell.

 What is surprising is that Python cannot discriminate between this:
 y = 100
 def f(a,x=y):
  print a+x
 f(1)
 101
 y=200
 f(1)
 101

 and this:

 def f(a,x=[]):
  print a+len(x)
  x.append(a)
 f(1)
 1
 f(1)
 2
 f(1,[1,2,3])
 4


 Is x supposed to be a default arg or a static arg (in the sense of a
 static var within a function as one finds in C)?

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

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


Re: what's the python for this C statement?

2008-10-20 Thread Chris Rebert
On Mon, Oct 20, 2008 at 2:56 AM, Michele [EMAIL PROTECTED] wrote:
 Hi there,
 I'm relative new to Python and I discovered that there's one single way
 to cycle over an integer variable with for:
 for i in range(0,10,1)

Actually, you want:

for i in range(10):

Since starting at 0 and using a step of 1 are the defaults.


 which is equivalent to:
 for (i = 0; i  10; i++)

 However, how this C statement will be translated in Python?

 for (j = i = 0; i  (1  H); i++)

There's no nice way to translate more complex 'for' statements like
that (unless you can calculate the end value somehow).
You basically just have to use a 'while' loop instead:

i = j = 0
while i  1  H:
#body goes here
i += 1

Since bit-shifting doesn't get used much in Python and iteration
through a generator or the items of a collection is more common, this
doesn't end up being a problem in practice.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com



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

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


Re: quick newbie syntax question

2008-10-20 Thread Chris Rebert
On Mon, Oct 20, 2008 at 12:08 PM, Robocop [EMAIL PROTECTED] wrote:
 Is it possible to do something like this syntactically:

 year = '2008'
 month = '09'
 limit = '31'
 for i in range(1,limit):

This previous line will fail. range() takes numbers, not strings.
Change 'limit' to an int.

  temp = Table.objects.filter(date = year'-'month'-'i)screwed

I believe you're looking for the string formatting syntax, to wit:

temp = Table.objects.filter(  date=%s-%s-%s % (year, month, i)  )

Note that you can let 'year' and 'month' be integers now, as they will
be converted to strings for you automatically.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

 up syntax
  ...do something with temp
 return

 I know that the syntax within the filter statement is wrong.  Is it
 even possible to do something like that?  Any help is always
 appreciated.
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: hiding modules in __init__.py

2008-10-20 Thread Chris Rebert
On Sat, Oct 18, 2008 at 12:03 PM, Brendan Miller [EMAIL PROTECTED] wrote:
 How would I implement something equivalent to java's package private in
 python?

 Say if I have

 package/__init__.py
 package/utility_module.py

 and utility_module.py is an implementation detail subject to change.

 Is there some way to use __init__.py to hide modules that I don't want
 clients to see? Or is the best practice just to name the module you don't
 want clients to use _utility_module and have it private by convention?

Generally the latter on account of Python's we are all consenting
adults here philosophy.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: How to execute a makefile from LINUX system.

2008-10-21 Thread Chris Rebert
On Mon, Oct 20, 2008 at 10:32 PM, gaurav kashyap
[EMAIL PROTECTED] wrote:
 Hi all,
 I am using Link-41b parser in my program.
 The windows version of it has an .exe file that can be executed using
 os.system command
 On Linux version,I have a makefile.

 so my question is:
 How to run the makefile using some python function.

Use the 'subprocess' module
(http://docs.python.org/library/subprocess.html#module-subprocess) to
run the 'make' command in the same working directory as the Makefile
with the appropriate target as an option.

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: I want to release the GIL

2008-10-21 Thread Chris Rebert
On Mon, Oct 20, 2008 at 10:12 PM, Piotr Sobolewski
[EMAIL PROTECTED] wrote:
 Hello,
 I have such program:

 import time
 import thread
 def f():
 global lock
 while True:
 lock.acquire()
 print thread.get_ident()
 time.sleep(1)
 lock.release()
 lock=thread.allocate_lock()
 thread.start_new_thread(f,())
 thread.start_new_thread(f,())
 time.sleep(60)

 As you can see, I start two threads. Each one works in an infinite
 loop.
 Inside that loop it acquires lock, prints its own id, sleeps a bit and
 then
 releases lock.

 When I run it, I notice that only one thread works and the other one
 never
 has a chance to run. I guess it is because the thread don't have a
 chance
 to release the GIL - after it releases the lock, it almost immediately
 (in
 the very next bytecode command) reacquires it. I know I can
 put time.sleep(0.01) command after between release and reacquire,
 but it
 doesn't seem elegant - why should I make my program sleep instead of
 work?

You let *one thread* sleep so that the *other thread* can wake, grab
the lock, and *work*.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Is there any simple way to release the GIL? Like:
 lock.release()
 thread.release_gil()
 ?

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

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


Re: importing a class thru a variable?

2008-10-21 Thread Chris Rebert
On Tue, Oct 21, 2008 at 4:07 PM, john [EMAIL PROTECTED] wrote:
 Hi,
 This is probably a question of questionable sanity, due to the fact I
 don't think I can explain this well. I'd like to have a script set up
 such that it imports a class that is named in the command line
 arguments as the first argument to the script.

 Let's say I have a script, command.py, and I'd like to run it like
 this:
 command.py class_id_like_to_import --option1 value1 --option2 value2

 where 'class_id_like_to_import' is a class name and --option1/value1
 and so on are arguments that get passed to that class.

 I know that trying to do something like:

  classname = sys.argv[1]
  import classname

Python import modules, not classes, but I believe you're looking for
the __import__() function.
See the first entry on http://www.python.org/doc/2.5.2/lib/built-in-funcs.html

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 doesn't exactly work. I've tried to google for something like this,
 and search the old posts to this newsgroup and haven't quite found
 anything resembling what I'm looking for.

 Thanks in advance, and apologies if this has been answered before...
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Function to Add List Elements?

2008-10-22 Thread Chris Rebert
On Wed, Oct 22, 2008 at 12:59 PM, Henry Chang [EMAIL PROTECTED] wrote:
 This seems like a simple problem, but I can't find a simple solution.

 Suppose I have two lists of integers.

 List A = [A1, A2, A3]
 List B = [B1, B2, B3]

 I just simply want a new list, such as:

 List C = [C1, C2, C3]

 where:

 C1 = A1 + B1
 C2 = A2 + B2
 C3 = A3 + B3

 Is there a simple function to do this?

A one-liner in fact:

summed = [sum(pair) for pair in zip(listA, listB)]

Explanation: pairs up the elements of listA and listB, sums each pair,
constructs a list of the sums.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks so much?

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


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


Re: Python Script Bug

2008-10-23 Thread Chris Rebert
On Thu, Oct 23, 2008 at 11:54 AM, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Hello everyone,
 I would like to know what isn't good in my script.
 #!/usr/bin/python
 # -*- coding: iso-8859-15 -*-
 from time import strftime
 import datetime
 t = input(datetime.date)

input() does not do what you think it does. You want raw_input().
raw_input() takes a string to prompt the user with and returns the
string the user enters.
You'll then pass the string to time.strptime() (along with a format
string) to parse it into a time tuple. You'll then pass part of the
time tuple to the datetime.date() constructor to get a date object.

 global t

'global' declarations are only allowed (and only make sense) inside a
function. Remove the above line.

Based on some of the errors you've made, I'd recommend reading through
Python's fine tutorial before going any further:
http://docs.python.org/tutorial/index.html

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

 print t.strftime(Day %w of the week a %A . Day %d of the month (%B).
 )
 print t.strftime(Day %j of the year (%Y), in week %W of the year.)
 raw_input()
 i get error :
print t.strftime(Day %w of the week a %A . Day %d of the month
 (%B). )
 AttributeError: 'tuple' object has no attribute 'strftime'
 Thanks for your Help
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: why would 'import win32com' fail?

2008-10-23 Thread Chris Rebert
On Thu, Oct 23, 2008 at 12:21 PM, bill [EMAIL PROTECTED] wrote:
 All,

 I am trying to access Excel from Python. Many of the examples started
 with:

  import win32com
  
  blah, blah

 I try that from my Python shell and it fails. What am I missing here?

It's not a standard library module. You'll need to install it from:
http://python.net/crew/mhammond/win32/Downloads.html

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com



 TIA,

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

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


Re: Will Python 3 be stackless?

2008-10-23 Thread Chris Rebert
On Thu, Oct 23, 2008 at 1:14 PM, Phillip B Oldham
[EMAIL PROTECTED] wrote:
 Will Python 3 be stackless? Or, rather, will it have any features
 similar to stackless' microthreads and channels?
 --
 http://mail.python.org/mailman/listinfo/python-list


No, it will definitely not. But it does have the new multiprocessing
module: 
http://docs.python.org/library/multiprocessing.html#module-multiprocessing

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to examine the inheritance of a class?

2008-10-23 Thread Chris Rebert
On Thu, Oct 23, 2008 at 6:36 PM, John Ladasky [EMAIL PROTECTED] wrote:
 Hello again!

 Suppose that I have several subclasses which inherit from a base
 class, thus:

 class Foo(object):

 class Spam1(Foo):

 class Spam2(Foo):

 class Spam3(Foo):

 etc.  The list of subclasses is not fully defined.  It is supposed to
 be extensible by the user.

 Many methods will differ between these classes.  However, there are
 operations which may be performed between two Foo objects, OR between
 any of Foo's derivatives.

 There are instances where I would like to perform type checking before
 carrying out the operation.  Rather than having to enumerate all of
 Foo's subclasses (which would defeat my intent of extending the list
 of subclasses anyway), I would like to see whether a class is DERIVED
 from Foo.  Where is this information stored in the class definition?

In __bases__, e.g. Spam1.__bases__, which would be (class '__main__.Foo',).
In practice, you probably just want to use  if isinstance(some_obj,
Foo):  which will be true for SpamN instances.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks!

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

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


Re: Global dictionary or class variables

2008-10-24 Thread Chris Rebert
On Fri, Oct 24, 2008 at 1:44 PM, Mr. SpOOn [EMAIL PROTECTED] wrote:
 Hi,
 in an application I have to use some variables with fixed valuse.

 For example, I'm working with musical notes, so I have a global
 dictionary like this:

 natural_notes = {'C': 0, 'D': 2, 'E': 4 }

 This actually works fine. I was just thinking if it wasn't better to
 use class variables.

 Since I have a class Note, I could write:

 class Note:
C = 0
D = 2
...

 Which style maybe better? Are both bad practices?

Depends. Does your program use the note values as named constants, or
does it lookup the values dynamically based on the note name?
If the former, then the class is marginally better, though putting the
assignments in a (possibly separate) module would probably be best. If
the latter, than the dictionary is fine.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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

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


Re: Database specialized in storing directed graphs?

2008-10-28 Thread Chris Rebert
On Mon, Oct 27, 2008 at 5:32 PM, Carl Banks [EMAIL PROTECTED] wrote:
 I was wondering if anyone had any advice on this.

 This is not to study graph theory; I'm using the graph to represent a
 problem domain.  The graphs could be arbitrarily large, and could
 easily have millions of nodes, and most nodes have a substantial
 amount of data associated with them.  Obviously I don't want a whole
 such graph in memory at once, so libraries the just deal with in-
 memory graphs are out.

 I know I could implement this with a relational DB, and I'd be fine
 with a library that was built on top of one.  But I'm hoping for
 specialzed behavior useful for graphs.

 For example, suppose I have a set of nodes called A.  It would be
 useful to know if any of these nodes are connected by paths that
 include no nodes in A.  I could, of course, do that by reading from
 the database and following the paths, but I clearly don't want to do
 that.  I would want instead to somehow cache the outside connectedness
 relationship between different nodes of A.  But then what happens if
 something changes elsewhere.  How is the cache for A notified, and can
 it be updated efficiently using graph theorems, rather than
 regenerated?

 It's very tricky; that's why I hope someone else has done it.

 I'm guessing no.

By sacrificing a goat at the altar of the Almighty Google, I was able
to locate a project I came upon a long while ago but couldn't remember
the name of that's vaguely like what you want, in that it's a graph
database: Neo4j - http://neo4j.org/ (and yes, it's in Java; sigh)
Not sure it's exactly what you're looking for, but anyway

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com



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

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


Re: Contracts for Python

2008-10-28 Thread Chris Rebert
On Tue, Oct 28, 2008 at 10:47 AM, Paulo J. Matos [EMAIL PROTECTED] wrote:
 Hi all,

 I am wondering if there is any work on contracts for Python. I could
 only find PEP316, however, I am wondering if there is any official
 support for it already (tools I mean), and if it is or if it will be
 officially supported in any of the next releases of Python.

No, it's not officially supported and there are currently no plans to
support it, though as PEP 316 is Deferred and not Rejected, it's
theoretically possible that it could be Accepted and added to the
language some day.
At any rate, there are several third-party libraries available that
allow you to use Design by Contract in Python, albeit without
language-level support.
See http://pypi.python.org/pypi?%3Aaction=searchterm=contractsubmit=search
for a list

Cheers,
Chris


 Cheers,
 --
 Paulo Jorge Matos - pocmatos at gmail.com
 Webpage: http://www.personal.soton.ac.uk/pocm
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Return lines in file that match string

2008-10-28 Thread Chris Rebert
On Tue, Oct 28, 2008 at 11:37 AM, Travis Kirstine
[EMAIL PROTECTED] wrote:
 I am new to python and could use some help with a fairly easy task.  I
 would like to return all lines in a file that have the string
 'coordinates' to a list.


from __future__ import with_statement

with open('path/to/file') as f:
desired_lines = [line.strip() for line in f if coordinates in line]

For your reference, that uses the with statement and list comprehensions.
It would also be advisable for you to read through the fine tutorial
at: http://docs.python.org/tutorial/index.html

Cheers,
Chris

 Regards,

 --
 Travis K.

 Toronto, Canada
 
 She knows there's no success like failure
 And that failure's no success at all.
 -Bob Dylan-
 
 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Default Argument Question

2008-10-29 Thread Chris Rebert
On Wed, Oct 29, 2008 at 9:14 AM, Paulo J. Matos [EMAIL PROTECTED] wrote:
 Hi all,

 Going through the tutorial brought up a question. Consider the functions:

 def f(a, L=[]):
L.append(a)
return L

 print f(3)
 print f(9)
 print f(7)

 def f1(i = 0):
i = i + 1
print i

 f1()
 f1()
 f1()
 f1()

 Since the f accumulates the values in L, I was expecting to see i
 printing 1,2,3,4 but this doesn't happen.
 Can someone please explain why and what is going on beneath the veil?

http://effbot.org/zone/default-values.htm explains this FAQ quite
well. Note that the accumulation behavior of lists is considered an
aberration and is usually not desired.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Cheers,

 --
 Paulo Jorge Matos - pocmatos @ gmail.com
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: split() and string.whitespace

2008-10-31 Thread Chris Rebert
On Fri, Oct 31, 2008 at 11:53 AM, Chaim Krause [EMAIL PROTECTED] wrote:
 I am unable to figure out why the first two statements work as I
 expect them to and the next two do not. Namely, the first two spit the
 sentence into its component words, while the latter two return the
 whole sentence entact.

 import string
 from string import whitespace
 mytext = The quick brown fox jumped over the lazy dog.\n

 print mytext.split()
 print mytext.split(' ')
 print mytext.split(whitespace)
 print string.split(mytext, sep=whitespace)

Also note that a plain 'mytext.split()' with no arguments will split
on any whitespace character like you're trying to do here.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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

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


Re: Efficient way to remove objects from a list

2008-11-03 Thread Chris Rebert
On Mon, Nov 3, 2008 at 1:40 AM, 一首诗 [EMAIL PROTECTED] wrote:
 Hi all,

 Today I wrote some code like this:


Build a new list as you go, then overwrite the old list with it.

unfinished = []

for m in self.messages:
if not m.finished:
  unfinished.append(m)
continue

#process the message


Remove the following code

fini = [m for m in self.messages if m.finished]
for m in fini:
self.messages.remove(m)

self.messages[:] = unfinished

This way you aren't calling .remove() multiple times and only iterate
through the list once.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 As you can, I want to find these finished messages in
 self.messages,
 process them, and then remove them from the list.

 Because a list can not be modified while iterating it,  I have to use
 a list fini to accomplish the target.

 I found a smell of bad performance here.
 Is there any faster ways?
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: wrapping a method function call?

2008-11-03 Thread Chris Rebert
On Mon, Nov 3, 2008 at 1:57 AM,  [EMAIL PROTECTED] wrote:
 Steven D'Aprano [EMAIL PROTECTED] wrote:
 Now you can monkey patch class A if you want. It's probably not a great
 idea to do this in production code, as it will effect class A everywhere.


 This is perfect for me.  The code in question is basically a protocol
 translator... it receives requests over the network, makes some calls,
 and returns the result translated back to the original protocol, so there's
 a single instance of each A,B, etc.

 A.p1 = precall(pre)(postcall(post)(A.p1))

 Is there a way to do this for all callable methods of A? e.g.

for x in callable_methods(A):
x = precall(pre)(postcall(post)(x))

for name, attr in A.__dict__.iteritems():
if callable(attr):
A.__dict__[name] = precall(pre)(postcall(post)(attr))

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks!
 Mark

 --
 Mark Harrison
 Pixar Animation Studios
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Is there a better/simpler way to filter blank lines?

2008-11-04 Thread Chris Rebert
On Tue, Nov 4, 2008 at 2:30 PM, tmallen [EMAIL PROTECTED] wrote:
 On Nov 4, 4:30 pm, [EMAIL PROTECTED] wrote:
 tmallen:

  I'm parsing some text files, and I want to strip blank lines in the
  process. Is there a simpler way to do this than what I have here?
  lines = filter(lambda line: len(line.strip())  0, lines)

 xlines = (line for line in open(filename) if line.strip())

 Bye,
 bearophile

 I must be missing something:

 xlines = (line for line in open(new.data) if line.strip())
 xlines
 generator object at 0x6b648
 xlines.sort()
 Traceback (most recent call last):
  File stdin, line 1, in module
 AttributeError: 'generator' object has no attribute 'sort'

 What do you think?

xlines is a generator, not a list. If you don't know what a generator
is, see the relevant parts of the Python tutorial/manual (Google is
your friend).
To sort the generator, you can use 'sorted(xlines)'
If you need it to actually be a list, you can do 'list(xlines)'

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: find an object ancestor

2008-11-05 Thread Chris Rebert
On Sun, Nov 2, 2008 at 1:16 PM, Michel Perez [EMAIL PROTECTED] wrote:
 HI all:

 imagine something like this:

 class father:
pass
 class son( father ):
pass

 I need to know the son ancestor class how can i know this.

Help on built-in function issubclass in module __builtin__:

issubclass(...)
issubclass(C, B) - bool

Return whether class C is a subclass (i.e., a derived class) of class B.
When using a tuple as the second argument issubclass(X, (A, B, ...)),
is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks


 ---
Red Telematica de Salud - Cuba
  CNICM - Infomed
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: List to Text back to List

2008-11-06 Thread Chris Rebert
On Thu, Nov 6, 2008 at 12:04 PM, SimonPalmer [EMAIL PROTECTED] wrote:
 Hi, I am looking for a way to convert a List of floating point numbers
 to and from text.  I am embedding it in an XML document and am looking
 for a neat way to serialise and de-serialise a list from a text node.
 I can easily write something to do it manually but I wondered whether
 List had native support to go to and from text.

 If not List, are there any other collections/arrays that do this?

It's not really a matter of the collection, but more a matter of
serialization format/library.

If you want the serialized representation to be human-readable, use
JSON (http://docs.python.org/library/json.html#module-json).
If that's not a requirement, use pickle
(http://docs.python.org/library/pickle.html#module-pickle).
Both modules can convert simple Python data, such as your list of
floats, to a bytestream and back again.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: List to Text back to List

2008-11-06 Thread Chris Rebert
On Thu, Nov 6, 2008 at 12:18 PM, SimonPalmer [EMAIL PROTECTED] wrote:
 On Nov 6, 8:11 pm, Chris Rebert [EMAIL PROTECTED] wrote:
 On Thu, Nov 6, 2008 at 12:04 PM, SimonPalmer [EMAIL PROTECTED] wrote:
  Hi, I am looking for a way to convert a List of floating point numbers
  to and from text.  I am embedding it in an XML document and am looking
  for a neat way to serialise and de-serialise a list from a text node.
  I can easily write something to do it manually but I wondered whether
  List had native support to go to and from text.

  If not List, are there any other collections/arrays that do this?

 It's not really a matter of the collection, but more a matter of
 serialization format/library.

 If you want the serialized representation to be human-readable, use
 JSON (http://docs.python.org/library/json.html#module-json).
 If that's not a requirement, use pickle
 (http://docs.python.org/library/pickle.html#module-pickle).
 Both modules can convert simple Python data, such as your list of
 floats, to a bytestream and back again.

 Cheers,
 Chris
 --
 Follow the path of the Iguana...http://rebertia.com



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



 I looked at pickle, but the problem is that I want my XML to be
 readable by languages other than python, so it sort of precludes it.
 JSON would be perfect, but I think the module only exists in 2.6, is
 that right?  Unfortunately I am bound to 2.4.

 It is looking more and more like I am going to have to roll my own.

The module is available as a third-party library for previous Python
versions at http://www.undefined.org/python/

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: etymology of list comprehension?

2008-11-06 Thread Chris Rebert
On Thu, Nov 6, 2008 at 1:19 PM,  [EMAIL PROTECTED] wrote:
 I googled and wiki'ed, but couldn't find a concise clear answer
 as to how python list comprehensions got their name.

 Who picked the name?  What was the direct inspiration, another
 language?  What language was the first to have such a construct?

According to Wikipedia, the SETL programming language was the first
one to have such a construct. My understanding is that Python took the
idea from Haskell, where the concept has the same name. The term
comprehension for the concept was first used in the NPL programming
language (Wikipedia again).

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 I get that it's based on set notation.

 Thanks!
 Mark

 --
 Mark Harrison
 Pixar Animation Studios
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: problem with regex, how to conclude more than one character

2008-11-06 Thread Chris Rebert
On Thu, Nov 6, 2008 at 11:06 PM,  [EMAIL PROTECTED] wrote:
 I always have no idea about how to express conclude the entire word
 with regexp,  while using python, I encountered this problem again...

 for example, if I want to match the string in test a string,
 re.findall(r[^a]* (\w+),test a string) will work, but what if
 there is not a but an(test a string)? the [^an] will failed
 because it will stop at the first character a.

 I guess people not always use this kind of way to filter words?
 Here comes the real problem I encountered:
 I want to filter the text both in td block and the span's
 title attribute

Is there any particularly good reason why you're using regexps for
this rather than, say, an actual (X)HTML parser?

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

 ## code #
 import re
 content='''tr align=center valign=middle class=CellCsstd
 valign=middleLA/tdtd valign=middle11/10/2008/tdtd
 valign=middle1340/1430/tdtd valign=middlePF1/5/tdtd
 valign=middlespan title=Understanding the stock market
 class=MouseCursorUnderstand/span/tdtd title=Charisma
 valign=middleCharisma/tdtd valign=middleBooked/tdtd
 valign=middle'''

 re.findall(r'''td valign=middle([^]+)/tdtd
 valign=middle([^]+)/tdtd valign=middle([^]+)/tdtd
 valign=middle([^]+)/tdtd valign=middlespan
 title=([^]*)''',content)

  code end 
 As you saw above,
 I get the results with LA,11/10/2008,1340/1430,PF1/5,Understanding
 the stock market
 there are two span block but I can just get the title attribute
 of the first span using regexp.
 for the second, which should be Charisma I need to use some kind of
 [^/td]* to match class=MouseCursorUnderstand/span/td,
 then I can continue match the second span block.

 Maybe I didn't describe this clearly, then feel free to tell me:)
 thanks for any further reply!
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: is it a bug in Module copy or i am wrong??

2008-11-07 Thread Chris Rebert
On Thu, Nov 6, 2008 at 11:59 PM, yoma [EMAIL PROTECTED] wrote:
 python version 2.5 in module copy

 we all know that copy have two method: copy() and deepcopy().
 and the explain is
 - A shallow copy constructs a new compound object and then (to the
  extent possible) inserts *the same objects* into it that the
  original contains.

 - A deep copy constructs a new compound object and then, recursively,
  inserts *copies* into it of the objects found in the original.

 so i try a example:
 import copy

 class A:
i = 1

 class B:
a = A()

Note that `a` is a class variable, not an instance variable. This ends
up being important.



 b = B()

 x=copy.copy(b)

 y=copy.deepcopy(b)

I believe these only copy the instance variables of `b`. They do NOT
copy the class `B` (IMHO, copying B would be weird and unexpected
behavior here anyway) or its constituent variables, such as `a`.


 print id(x.a), id(b.a)

 print id(y.a), id(y.a)

 the result:
 14505264 14505264
 14505264 14505264

Thus this makes sense. These all refer to B's variable `a`, which is a
class variable and therefore not copied by copy() or deepcopy()-ing
`b`, an *instance* of class B.
The fact that you can access `a` through B instances does not mean
that `a` belongs to any instance of B and is merely a result of how
Python's object system works.

Disclaimer: I am not a CPython dev and did not look at the `copy`
module's sources.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 So maybe i have a wrong understand to deep copy and shallow copy or
 it is  a bug ?

 please help me!!



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

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


Re: [urllib2 + Tor] How to handle 404?

2008-11-07 Thread Chris Rebert
On Fri, Nov 7, 2008 at 12:05 AM, Gilles Ganault [EMAIL PROTECTED] wrote:
 Hello

I'm using the urllib2 module and Tor as a proxy to download data
 from the web.

 Occasionnally, urlllib2 returns 404, probably because of some issue
 with the Tor network. This code doesn't solve the issue, as it just
 loops through the same error indefinitely:

 =
 for id in rows:
url  = 'http://www.acme.com/?code=' + id[0]
while True:
try:
req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req).read()
except HTTPError,e:
print 'Error code: ', e.code
time.sleep(2)
continue
else: #should align with the `except`
break
handle_success(response) #should align with `url =` line

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

 =

 Any idea of what I should do to handle this error properly?

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

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


Re: List of modules available for import inside Python?

2008-08-27 Thread Chris Rebert
On Wed, Aug 27, 2008 at 9:21 PM, ssecorp [EMAIL PROTECTED] wrote:
 Is there a way to view all the modules I have available for import
 from within Python?
 Like writing in the interpreter:
 import.modules


 Also, is there anything like Cpan for Python?

The closest thing would be PyPI (the Python Package Index)
[http://pypi.python.org/pypi], and easy_install (a package manager for
Python) [http://peak.telecommunity.com/DevCenter/EasyInstall].

- Chris

Follow the path of the Iguana...
Rebertia: http://rebertia.com
Blog: http://blog.rebertia.com

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

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


Re: epoch seconds from a datetime

2008-08-28 Thread Chris Rebert
On Thu, Aug 28, 2008 at 10:18 AM, Richard Rossel [EMAIL PROTECTED] wrote:
 Hi friends,
 I need a little help here, I 'm stuck with epoch calculation issue.
 I have this datetime:
 date_new = datetime(*time.strptime('20080101T00','%Y%m%dT%H%M%S')
 [0:6])
 This date_new is in UTC
 Now I need to know the seconds since epoch of this new date, so I run
 this:
 seconds = int(time.mktime(date_new.timetuple()))
 but the seconds returned belongs to :
 Tue, 01 Jan 2008 03:00:00 GMT
 because the  localtime is in timezone 'America/Santiago': -3

 I fix this trying to alter the TZ with time.tzset():
  os.environ['TZ'] = 'UTC'
 time.tzset()

  and now I can gets the right epoch, but I can't restore the
 previous TimeZone, I try with:
 os.environ['TZ'] = '', but the time.tzset() doesn't back to the
 original ( America/Santiago)

I think you need to del os.environ['TZ'] rather than setting it to the
empty string.

On my box:
Python 2.5.1 (r251:54863, Feb  4 2008, 21:48:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
 import os, time
 time.asctime()
'Thu Aug 28 11:19:57 2008'
 #that's my correct local time
 time.tzname
('PST', 'PDT')
 #that's my correct timezone
 os.environ['TZ'] = 'UTC'
 time.tzset()
 time.tzname
('UTC', 'UTC')
 time.asctime()
'Thu Aug 28 18:20:33 2008'
 #we're clearly in UTC now
 del os.environ['TZ'] #this is the key line
 time.tzset()
 time.tzname
('PST', 'PDT')
 time.asctime()
'Thu Aug 28 11:21:05 2008'
 #and now we're back to my original timezone

Regards,
Chris

Follow the path of the Iguana...
Rebertia: http://rebertia.com
Blog: http://blog.rebertia.com


 A solution should be set the os.environ['TZ']   to  'America/Santiago'
 but I can't make a TZ hardcode because
 the software should works on different timezones.

 So the question, how can restore the system into original timezone, or
 how to know the seconds since epoch
 from UTC datetime without change the local system TIMEZONE.

 please help

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

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


Re: Multiple values for one key

2008-08-28 Thread Chris Rebert
On Thu, Aug 28, 2008 at 10:02 AM, Ron Brennan [EMAIL PROTECTED] wrote:
 I have another question.

 How would like to be able to add the contents on the values for one key.

 key['20001']:[978, 345]

I'm assuming that by this you meant:
assert the_dict['20001'] == [978, 345]


 How can I do this?

sum(the_dict['20001']) #= 1323

Regards,
Chris

Follow the path of the Iguana...
Rebertia: http://rebertia.com
Blog: http://blog.rebertia.com


 Thanks,
 Ron

 On Thu, Aug 28, 2008 at 11:56 AM, Bruno Desthuilliers
 [EMAIL PROTECTED] wrote:

 norseman a écrit :

 Terry Reedy wrote:


 Ron Brennan wrote:

 Hello,
   How would I create a dictionary that contains multiple values for one
 key.

 Make the value a collection object (set or list if you plan to add and
 delete).

  I'd also like the key to be able to have duplicate entries.

 Dict keys must be hashable and unique.

 tjr

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

 
 First part I understand, second is still giving me a problem.

 For some reason I still want keys to be dbf column headers.
 like:

 name:address:zip so forth
  --- --- --
 guy: unknown:0
 girl: 123 tiny street:12345
 boy:321 here:3
 gal:999 over there: 5
 so forth

 Thus one key has many values. And you can then index on whatever key(s)
 you wish - name,zip...

 You can either use 1/ a list of dicts, or 2/ a dict mapping keys to lists.

 1/
 records = [
   {name:guy, address:unknown,zip:0},
   {name:girl, address:123 tiny street,zip:12345},
   {name:boy, address:321 here,zip:3},
   {name:gal, address:999 over there,zip:5},
 ]

 keys = (name, address, zip)

 print :.join(keys)
 print - * len(:.join(keys))
 for record in records:
data = [record[key] for key in keys]
print :.join(data)


 2/
 records = dict(
name=[guy, girl, boy, gal],
address=[unknown,123 tiny street,321 there,999 over there],
zip=[0, 12345, 3, 5]
)

 keys = (name, address, zip)
 nb_records = len(records[keys[0]])

 print :.join(keys)
 print - * len(:.join(keys))
 for i in xrange(nb_records):
data = [data[key][i] for key in keys]
print :.join(data)


 You are of course entitled the right to prefer the second solution, but
 then I hope I'll never have to maintain your code, since it's obviously not
 an appropriate data structure.

 With billions plus records,

 With billions plus records, it may be time to move to a serious RDBMS.
 Which btw will provide solution 1, or a lighter version of it using a list
 of tuples, ie:

 cursor = connection.cursor()
 cursor.execute(select name, address, zip from peoples)
 records = cursor.fetchall()

 # at this time, you have :
 #records = [
 #   (guy, unknown,0,),
 #   (girl, 123 tiny street,12345,),
 #   (boy, 321 here,3,),
 #   (gal, 999 over there, 5,),
 #]


 (snip)

 OK - I know I missed the whole concept of a Python Dictionary.

 Bad thing for you, since it's the central datastructure in Python.

 I haven't read anything as yet that gives a clear picture of what it is
 and what it is for.

 Then you failed to read the FineManual's tutorial, which is where you
 should have started:

 http://docs.python.org/tut/node7.html#SECTION00750

 Do yourself a favour : read the above first, then if you still have
 questions about dicts, we'll gladly try to help.

 And do yourself another favour : learn about SQL, relational model and
 RDBMS.

 (snip description of why the OP *really* wants a RDBMS)
 --
 http://mail.python.org/mailman/listinfo/python-list



 --
 FYI, my email address is changing. My rogers account will be deactivated
 shortly.  From now on please use:
 [EMAIL PROTECTED]

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

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

Re: re.compile versus r''

2008-08-28 Thread Chris Rebert
On Thu, Aug 28, 2008 at 12:23 PM, Terrence Brannon [EMAIL PROTECTED] wrote:
 Hello, I'm using a tool (PLY) which apparently expects the tokens to
 be created using r''

 But because one token is a rather complex regular expression, I want
 to create the regular expression programmatically.

 How can I generate a string and then create something of the same type
 that the r'' function does?

The r prefix isn't a function or a type, it's merely a special
literal syntax for strings that's handy when you're writing regexes
and therefore have to deal with another level of backslash escaping.
See the second to last paragraph of
http://docs.python.org/ref/strings.html  for more info.

Regards,
Chris


 Concretely, in the program below, consonant is not the same type as
 t_NAME, but I assume that it needs to be for PLY to use it for
 tokenizing:

 import re

 t_NAME   = r'[a-zA-Z_][a-zA-Z0-9_]*'

 guttural   = 'kh?|gh?|\n'
 palatal= '(?:chh?|jh?|\~n)'
 cerebral   = '\.(?:th?|dh?|n)'
 dental = '(?:th?|dh?|n)'
 semivowel  = '[yrlv]'
 sibilant   = '[\\.]?s'
 aspirant   = 'h'

 consonant = re.compile('|'.join([guttural , palatal , cerebral ,
 dental , semivowel , sibilant , aspirant]))

 print consonant
 print t_NAME
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: When to use try and except?

2008-08-29 Thread Chris Rebert
On Fri, Aug 29, 2008 at 10:56 AM, cnb [EMAIL PROTECTED] wrote:
 On Aug 29, 7:40 pm, Daniel [EMAIL PROTECTED] wrote:
 On Aug 29, 11:23 am, cnb [EMAIL PROTECTED] wrote:

  If I get zero division error it is obv a poor solution to do try and
  except since it can be solved with an if-clause.

  However if a program runs out of memory I should just let it crash
  right? Because if not then I'd have to write exceptions everywhere to
  prevent that right?

  So when would I actually use try-except?

  If there can be several exceptions and I just want to catch 1 or 2?
  Like
  try:
  blahaba
  except SomeError:
  do something

 I'm not sure whay you're trying to do, but I think catching a
 ZeroDivisionError exception is a good use of try-except.

 I'm also not sure that I would say you just let a program crash if it
 runs out of memory.  I would think that from the user perspective, you
 would want to check memory conditions and come up with an exception
 indicating that some memory threshold has been reached.  When that
 exception is raised you should indicate that to the user and exit
 gracefully.


 A ZeroDivisionError is better avoided wth an if-clause, don't you
 think? It is a predictable exception...

Basically, there's a general principle (EAFP: Easier to ask
forgiveness than permission) in Python to just try something and
then catch the exception if something goes wrong. This is in contrast
to e.g. C where you're supposed to Look before you leap (LBYL) and
check for possible error conditions before performing the operation.
One of the main advantages of the Python approach is that the
operation itself comes first in the code:

try:
a = b/c
except ZeroDivisionError:
#handle it

versus the LBYL approach:

if c == 0:
#handle error
a = b/c

where if the error handling code isn't really short, it ends up
distracting you from the operation you're actually trying to perform.
This individual case (division by 0) might not be the best example due
to its simplicity, but you get the general point.

- Chris

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

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


Re: How to delete a ast character from a string?

2008-08-29 Thread Chris Rebert
On Fri, Aug 29, 2008 at 11:25 AM,  [EMAIL PROTECTED] wrote:
 Hi,

 I've a list some of whose elements with character \.
 I want to delete this last character from the elements that have this
 character set at their end,

 I have written a small program, unfortunately this does not work:

 dirListFinal = []
 for item in dirList:
print item
if item.endswith('\\') == True:

You san simplify that line to just:
if item.endswith('\\'):

item = item[0:-1] # This one I googled and
 found to remove the last character /

And you don't need the leading 0, so just use:
item = item[:-1]

dirListFinal.append(item)
else:
dirListFinal.append(item)

And those last 3 lines are a bit redundant. Just put one

  dirListFinal.append(item)

at the same indentation level as the if and delete those 3 lines.

Not that these changes will necessarily fix your program, but they do
make it easier to comprehend for the reader.

- Chris



 item.endswith() does not seem to be working.

 Please help
 --
 Regrads,
 Rajat
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Using class-attribute as key to sort?

2008-08-29 Thread Chris Rebert
Just use the key argument to list.sort; e.g.

class Foo(object):
def __init__(self, x):
self.x = x
def __repr__(self):
return Foo:+str(self.x)

foos = [Foo(75), Foo(10), Foo(-1)]
foos.sort(key = lambda foo: foo.x)
print foos #= [Foo:-1, Foo:10, Foo:75]

- Chris

Follow the path of the Iguana...
http://rebertia.com

On Fri, Aug 29, 2008 at 11:22 AM, cnb [EMAIL PROTECTED] wrote:
 In median grade, can I sort on Review-grade somehow?
 something like:
 sr = self.reviews.sort(key=self.reviews.instance.grade)

 class Review(object):
def __init__(self, movieId, grade, date):
self.movieId = movieId
self.grade = grade
self.date = date

 class Customer(object):
def __init__(self, idnumber, review):
self.idnumber = idnumber
self.reviews = [review]

def addReview(self, review):
self.reviews.append(review)

def averageGrade(self):
tot = 0
for review in self.reviews:
tot += review.grade
return tot / len(self.reviews)

#general sort that takes list+spec of objectkey to sort on?
def sortReviews(self):
def qsort(lista):
if len(lista) != 0:
return qsort([x for x in lista[1:] if x.grade 
 lista[0].grade]) + [lista[0]] + \
   qsort([x for x in lista[1:] if x.grade =
 lista[0].grade])
else:
return []
return qsort(self.reviews)

def medianGrade(self):
length = len(self.reviews)
sr = self.sortReviews()
#sr = self.reviews.sort(key=self.reviews.instance.grade)
if length % 2 == 0:
return (sr[int(length/2)].grade + sr[int(length/
 2-1)].grade) / 2
else:
if length == 1:
return sr[0].grade
else:
return sr[int(round(length/2)-1)].grade
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Is this a closure?

2008-08-31 Thread Chris Rebert
Yes, printReviews() is a closure. In particular, it's closing over the
variable self, which it's getting lexically from printSelf().
- Chris

On Sun, Aug 31, 2008 at 4:53 PM, ssecorp [EMAIL PROTECTED] wrote:
 A method on a class:

 def printSelf(self):
def printReviews():
for review in self.reviews:
review.printSelf()
print Idnbr: , self.idnumber, Reviews: , printReviews()

 I don't have to pass an argument to printReviews because everything
 defined inside printSelf is aware of outer variables? Or is that
 wrong? If it is right, is this what a closure means?

 Because Python is lexically scoped right? Is lexical scope+closures =
 organized dynamic scope kind of if you get my point?

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



-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Some problems with classes

2008-08-31 Thread Chris Rebert
On Sun, Aug 31, 2008 at 6:39 PM, ssecorp [EMAIL PROTECTED] wrote:
 Why/how is it possible to add variables like this? I don't understand
 this mechanism:
 http://docs.python.org/tut/node11.html#SECTION001133

Under the covers, Python objects are implemented using dictionaries,
so adding an attribute just adds a new key-value pair to the object's
internal dictionary (which, incidentally, you can access as
someobj.__dict__).


 class Employee:
pass

 john = Employee() # Create an empty employee record

 # Fill the fields of the record
 john.name = 'John Doe'
 john.dept = 'computer lab'
 john.salary = 1000

 ---

 Also, I can't get multiple inheritance to work.

 Don't mind that the a vegan obviously don't inherit from an animal and
 a vegetable. I didn't come up with anything better, it is just to
 learn about inheritance.


 class Animal(object):
def __init__(self, name, weight):
self.name = name
self.weight = weight

def speak(self):
print speak

 class Vegetable(object):
def __init__(self, name, volume):
self.name = name
self.volume = volume

def split(self):
print tjoff

 class Vegan(Animal, Vegetable):
#pass
def __init__(self, name, attacks):
self.name = name
self.attacks = attacks



 Traceback (most recent call last):
  File C:/Python25/Progs//Movie.py, line 42, in module
class ActionComedy(Movie, ActionMovie):
 TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
 order (MRO) for bases Movie, ActionMovie

The class names in error message here don't match the classes you
declared above. Give us the actual code you're using or at least a
stub version.




 also, when inheriting, can I inherit __init__() somehow? If I want the
 same attributes but perhaps some additional methods for example.

Use super() to call your superclasses' __init__() methods. See
super()'s entry in http://docs.python.org/lib/built-in-funcs.html for
more info.

- Chris


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


-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How Compute # of Days between Two Dates?

2008-08-31 Thread Chris Rebert
Have you tried using subtraction on datetime.date objects
(http://docs.python.org/lib/datetime-date.html)? It produces a
timedelta which should be very close to what you want.

- Chris

On Sun, Aug 31, 2008 at 7:38 PM, W. eWatson [EMAIL PROTECTED] wrote:
 That's the question in Subject. For example, the difference between
 08/29/2008 and 09/03/2008 is +5. The difference between 02/28/2008 and
 03/03/2008 is 4, leap year--extra day in Feb. I'm really only interested in
 years between, say, 1990 and 2050. In other words not some really strange
 period of time well outside our current era of history.

 --
   W. eWatson

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7 N, 121° 2' 32 W, 2700 feet

Web Page: www.speckledwithstars.net/

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




-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list

Re: How do I adjust the font size on IDLE when running on Mac OS 10.5.4? TIA.

2008-09-02 Thread Chris Rebert
Same as on all the other platforms.

1. Open IDLE
2. Go Options - Configure IDLE...
3. Choose the Fonts/Tabs section
4. Use the Size pulldown box

- Chris

On Tue, Sep 2, 2008 at 6:26 AM, Malcolm Lewis [EMAIL PROTECTED] wrote:


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




-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Py 2.6 changes

2008-09-02 Thread Chris Rebert
On Mon, Sep 1, 2008 at 6:02 PM, Mensanator [EMAIL PROTECTED] wrote:
 On Sep 1, 6:55�pm, [EMAIL PROTECTED] wrote:
 Steven D'Aprano:

  productory() -- I don't know that function, and googling mostly comes up
  with retail product searches. Do you mean product(),

 Darn my English, you are right, sorry, I meant a product() of
 course :-)

 But the name product() has already been taken by itertools to
 mean Cartesian Product.

We have this thing called namespacing and it's one honking great
idea that's perfect for these situations.

- Chris



 Bye,
 bearophile

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



-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list

Re: Pass same parameter in Recursive function

2008-09-02 Thread Chris Rebert
Assuming the function is tail-recursive or the unchanging arguments
are immutable, just use a closure:

def func(self, x, y, A, B, C):
def _func(x,y):
return _func(g(A,B,C,x), h(A,B,C,y)) #recurse
return _func(x, y)

I'm unsure as to the performance impact of this though.

- Chris

On Tue, Sep 2, 2008 at 8:20 PM, Davy [EMAIL PROTECTED] wrote:
 Hi all,

 Sometimes I need to pass same parameter in recursive function. From my
 point of view, the style is redundant, and I don't what to use some
 global style like self.A, self.B, Is there any other choice?

 For example,

 def func(self, x, y, A, B, C):
  #x, y change in recursive call
  #A, B, C change in the first layer function call, but did not change
 in recursive call
  if (...):
func(x, y, A, B, C)
  else(...):
func(x, y, A, B, C)

 Best regards,
 Davy
 --
 http://mail.python.org/mailman/listinfo/python-list


-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: use str as variable name

2008-09-04 Thread Chris Rebert
On Thu, Sep 4, 2008 at 12:25 AM, Mathieu Prevot
[EMAIL PROTECTED] wrote:
 Hi,

 I have a program that take a word as argument, and I would like to
 link this word to a class variable.

 eg.
 class foo():

You should subclass 'object', so that should be:
class Foo(object):

  width = 10
  height = 20

 a=foo()
 arg='height'
 a.__argname__= new_value

You're looking for the setattr() built-in function. In this exact case:
setattr(a, arg, new_value)

This is probably covered in the Python tutorial, please read it.

Regards,
Chris


 rather than :

 if arg == 'height':
  a.height = new_value
 elif arg == 'width';
  a.width = new_value

 Can I do this with python ? How ?

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


-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting .doc to .txt in Linux

2008-09-04 Thread Chris Rebert
I'd recommend using one of the Word-txt converters for Linux and just
running it in a shell script:
* http://wvware.sourceforge.net/
* http://www.winfield.demon.nl/

No compelling reason to use Python in this instance. Right tool for
the right job and all that.

- Chris

On Thu, Sep 4, 2008 at 12:54 PM,  [EMAIL PROTECTED] wrote:
 Hi Everyone,

 I had previously asked a similar question,
 http://groups.google.com/group/comp.lang.python/browse_thread/thread/2953d6d5d8836c4b/9dc901da63d8d059?lnk=gstq=convert+doc+txt#9dc901da63d8d059

 but at that point I was using Windows and now I am using Linux.
 Basically, I have some .doc files that I need to convert into txt
 files encoded in utf-8.  However, win32com.client doesn't work in
 Linux.

 It's been giving me quite a headache all day.  Any ideas would be
 greatly appreciated.

 Best,
 Patrick

 #Windows Code:
 import glob,os,codecs,shutil,win32com.client
 from win32com.client import Dispatch

 input = '/home/pwaldo2/work/workbench/current_documents/*.doc'
 input_dir = '/home/pwaldo2/work/workbench/current_documents/'
 outpath = '/home/pwaldo2/work/workbench/current_documents/TXT/'

 for doc in glob.glob1(input):
WordApp = Dispatch(Word.Application)
WordApp.Visible = 1
WordApp.Documents.Open(doc)
WordApp.ActiveDocument.SaveAs(doc,7)
 WordApp.ActiveDocument.Close()
 WordApp.Quit()

 for doc in glob.glob(input):
txt_split = os.path.splitext(doc)
txt_doc = txt_split[0] + '.txt'
txt_doc_path = os.path.join(outpath,txt_doc)
doc_path = os.path.join(input_dir,doc)
shutil.copy(doc_path,txt_doc_path)
 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Case-insensitive string compare?

2008-09-04 Thread Chris Rebert
On Thu, Sep 4, 2008 at 3:37 PM, Robert Dailey [EMAIL PROTECTED] wrote:
 On Thu, Sep 4, 2008 at 5:21 PM, Fredrik Lundh [EMAIL PROTECTED]
 wrote:

 Robert Dailey wrote:

 I currently have a dictionary object that I'm doing the following with:

 if lib not in stage_map:
# ... do stuff ...

 However, this will perform a case-sensitive comparison between lib and
 each key in stage_map. Is there a way to make this do a case-insensitive
 comparison instead?

 dictionary lookups use the exact value.  to make a case-insensitive
 lookup, use key.lower() instead of key when creating the dictionary, and
 then do

if lib.lower() not in state_map:
...

 So you're saying to ensure that stage_map's keys are initially lower-case to
 begin with? Well, I can't do this either since the case of the keys is
 actually valuable later on. It's only for the purposes of this specific
 comparison operation that the case should be ignored.

Then store the string in its original case in the value part of the
key-value pair:

stage_map[key.lower()] = (key,whatever)

- Chris


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




-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Very simple - please help

2008-11-07 Thread Chris Rebert
On Fri, Nov 7, 2008 at 8:52 PM, pineapple [EMAIL PROTECTED] wrote:
 I am not a python programmer, but am being forced to port one of my
 (smalltalk) applications to python for pragmatic reasons (python is
 embedded with a graphics package I am switching over to, so to use the
 graphics package I am essentially forced to use python).  Okay, enough
 background.

 At any rate, in my smalltalk solution, in order to avoid an if-then-
 else chain of if this command, do this function, else if this command
 do another function... I have commands set up in a dictionary.  I
 read the command integer, then key it into the dictionary to see what
 method/function to call.

 #Conceptual representation of dictionary with keys and values:

 1: do_command1
 2: do_command2
 3: etc...

 Trying to set up the same thing in python, it seems the lambda
 expression is what I need.  So I set up a simple class to test this,
 with some simple code as follows:

 ###
 class Blah(list):
pass

 commands = {1: (lambda: Blah())}
 ###

 This is accepted by the interpreter, no problem.  If I type commands
 into the interpreter I get the dictionary back showing the key '1'
 attached to the lambda expression.  If I type commands[1] into the
 interpreter, I get the lambda function back.  However, when I try to
 invoke the lambda function with a commands[1](), I get a global
 name 'Blah' is not defined.  I find this error odd, because if I do a
 Blah(), I get back a [] as expected (a list).

The code you gave works perfectly:

chris ~ $ python
Python 2.5.1 (r251:54863, Feb  4 2008, 21:48:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type help, copyright, credits or license for more information.
 class Blah(list):
... pass
...
 commands = {1: (lambda: Blah())}
 commands[1]()
[]

Please post some of the actual code so that we can determine the problem.
Taking a guess, I'd suspect Blah and commands are in different modules
and you didn't import Blah into commands' module, hence why Python
can't find it. But we'd need some more details to be able to determine
that.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 For a day, I have tried everything under the sun I know to try.  For
 instance, I thought perhaps lambdas don't work with methods, so I
 wrapped the method call in a function.  But I get the same error.  I
 have spent a day online googling this error, but have found nothing to
 help me.

 Can a guru out there help a python newbie with this?  I figure you can
 spot the problem in, oh, 5 seconds or less?

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

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


Re: replacing characters within a string

2008-11-08 Thread Chris Rebert
On Sat, Nov 8, 2008 at 9:16 PM, John Smith [EMAIL PROTECTED] wrote:
 Hi,

 I coded a python script that lets me parse a csv file into html code with a
 certain format, but I would like to replace every  and  character that
 appears within each column entry of the csv file (they are parsed as
 strings) with the html equivalents of lt; and gt;.

You want the cgi.escape() function -
http://docs.python.org/library/cgi.html#cgi.escape

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 example csv file row:
 FIXED,All,Enable audio entry

 and I want to replace audio with lt;audiogt; before I do a

 pThis is a  + str(array[0]) +  bug that applies to  + str(array[1]) +
  platforms and has the description:  + str(array[2]) + ./p

 to get the following html code:

 pThis is a FIXED bug that applies to All platforms and has the
 description: Enable lt;audiogt; entry./p

 (sometimes  appears twice or thrice and sometimes only  appears so they
 are not necessarily appearing together, e.g. - instead of something)

 How should I go about doing it?

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

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


Re: break up a value in a list to a list of individual items

2008-11-09 Thread Chris Rebert
On Sun, Nov 9, 2008 at 2:38 AM, r3bol [EMAIL PROTECTED] wrote:
 Hi, sorry to post this, but I've had a really hard time finding how to
 do it.
 Q.
 How can I break up a value in a list to a list of individual items
 (preferably without importing any modules)?
 Like...
 ['12345'] (string)
 to
 [1, 2, 3, 4, 5] [numbers]

nums = [int(char) for char in '12345']

Note also that:
list(1234) == [1, 2, 3, 4]

And do be sure to read one of the several fine Python tutorials.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: [Newbie] Strange output from list

2008-11-11 Thread Chris Rebert
On Tue, Nov 11, 2008 at 12:56 AM, Gilles Ganault [EMAIL PROTECTED] wrote:
 On Mon, 10 Nov 2008 20:02:39 -0600, Andrew [EMAIL PROTECTED] wrote:
sql = 'SELECT id FROM master'
rows=list(cursor.execute(sql))
for id in rows:
   sql = 'SELECT COUNT(code) FROM companies WHERE code=%s' % id[0]
   result = list(cursor.execute(sql))
   print Code=%s, number=%s % (id[0],result[0][0])

Using liberal term rewriting, consider the following rough
equivalencies in the code:

id[0] == rows[INDEX_HERE][0] == list(cursor.execute(sql))[INDEX_HERE][0]
result[0][0] == list(cursor.execute(sql))[0][0]

Note that in both cases, the list is sliced twice; the for-loop just
conceals the `[INDEX_HERE]` implicit slicing that is caused by
iterating over the list.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

Notice the extra [0] index on the result

In English:
Item zero of the tuple that is item zero of result

 Thanks, it worked. But why does id[0] return the value of the first
 (and only) column as I expected it, while I need to use result[0]
 [0] to access the first column?
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Printing a status line from a python script

2008-11-11 Thread Chris Rebert
On Tue, Nov 11, 2008 at 11:02 AM, Chris Seymour [EMAIL PROTECTED] wrote:
 Hi All,
 I am working on a python script for my colleague that will walk a
 directory and search in the different files for a specific string.
 These pieces I am able to do.  What my colleague wants is that when
 she runs the script the filename is replaced by the current file that
 is being processed.  So instead of seeing a series of files being
 listed down the page, she only wants to see the file currently being
 processed.

 I am not sure if this is even possible.  Any thoughts would be greatly
 appreciated.

Have you tried using carriage returns (\r)?

chris ~ $ python
Python 2.5.1 (r251:54863, Feb  4 2008, 21:48:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type help, copyright, credits or license for more information.
 for i in range(10):
... print '\r'+str(i),
9


Note how each line gets overwritten by the next so that we only see
the final number output (9).

But really, I don't see a good reason to do this. So what, the output
takes up some extra lines on the terminal? Big whoop. Your colleague
can either pipe the script to `less` or a file if it really bothers
them. And that way you get a list of all files processed, which can
often come in handy in my experience.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks.

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

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


Re: Close access to the base class public methods

2008-11-11 Thread Chris Rebert
On Tue, Nov 11, 2008 at 11:16 AM, RinKaMeAri [EMAIL PROTECTED] wrote:
 On Nov 11, 9:12 pm, Steve Holden [EMAIL PROTECTED] wrote:
 RinKaMeAri wrote:
  Hi!
  Could you imagine any way to block access to the base class public
  methods?
  Here is an example:
  class B:
  def public_method():
  pass

  class A(B):
  def public_a_method():
   pass

  def a = A()

  Is there any way to block the call a.public_method() without any
  changes to B class?
  Thank you!

 The simplest way would be to override B.public_method within A by
 defining A.public_method to raise a NotImplementedError or similar
 exception. Though of course this then begs the question of why A would
 need to subclass B in the first place, but I assume there would be
 methods you *did* want to implement.

 snip

 BTW, what do you mean to subclass B in the *first place*?

Because you're inheriting from A and yet you don't want to inherit a
certain part of A, in this case public_method(), it's usually a sign
something is wrong with your class hierarchy; otherwise, you could
just inherit from something else which would have just the part of A
you want to inherit; it's a so-called code smell, specifically
Refused Bequest I believe.

See this link into Fowler's Refactoring for more info on Refused
Bequest and the other code smells:
http://books.google.com/books?id=1MsETFPD3I0Cpg=PA87lpg=PA87dq=refused+bequestsource=blots=pKN4o0QJc7sig=rYT4lfWxhKijvNHpLYqk8DY5Epwhl=ensa=Xoi=book_resultresnum=3ct=result

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: multiple breaks

2008-11-13 Thread Chris Rebert
On Thu, Nov 13, 2008 at 2:07 AM, TP [EMAIL PROTECTED] wrote:
 Hi everybody,

 Several means to escape a nested loop are given here:

 http://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python

 According to this page, the best way is to modify the loop by affecting the
 variables that are tested in the loops. Otherwise, use exception:

 If, for some reason, the terminating conditions can't be worked out,
 exceptions are a fall-back plan.

 In the following example, is this possible to affect the two iterators to
 escape the two loops once one j has been printed:


Non-exception alternative:

done = False
 for i in range(5):
for j in range(i):
   print j
done = True
break
   # I would type break 2 in shell bash
   # In C, I would set j=i-1 and i=4
   # In Python, is this possible to affect the two iterators?
if done:
break

 Or the only means is to use exception?

No, you could add a boolean variable and a break condition like above.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks in advance

 Julien

 --
 python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.91+,\'Z
 (55l4('])

 When a distinguished but elderly scientist states that something is
 possible, he is almost certainly right. When he states that something is
 impossible, he is very probably wrong. (first law of AC Clarke)
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: unittest exits

2008-11-13 Thread Chris Rebert
On Thu, Nov 13, 2008 at 11:01 AM, Alan Baljeu [EMAIL PROTECTED] wrote:
 When I call unittest.main(), it invokes sys.exit().  I would like to run 
 tests without exiting.  How can I?

There's probably a better way that stops it from trying to exit in the
first place, but here's a quick kludge:

try:
unittest.main()
except SystemExit:
pass

sys.exit() does its job by noting the return code and then raising the
SystemExit exception, which you are free to catch.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com



  Alan Baljeu


  __
 Instant Messaging, free SMS, sharing photos and more... Try the new Yahoo! 
 Canada Messenger at http://ca.beta.messenger.yahoo.com/
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: To throw or to throw not?

2008-11-13 Thread Chris Rebert
On Thu, Nov 13, 2008 at 5:11 PM, Emanuele D'Arrigo [EMAIL PROTECTED] wrote:
 I'm pondering on what is a bit of a philosophical dilemma.
 When should I throw an exception and when should I not?

 Suppose I have myFunc1() calling myFunc2() which in turn calls myFunc3
 ().
 Suppose myFunc3() has detected a problem. What should it do?

 Throw an exception, forcing myFunc2() to handle it and/or trigger
 another exception for myFunc1() to deal with? Or should it simply
 return a meaningful error code, for myFunc2() and myFunc1() to handle
 as an option but not forcing them to do so?

Depends on how serious the error is (e.g. str.find() returns -1 rather
than raising an exception if it can't find the substring), but 98% of
the time, you'll want to raise an exception; it's Pythonic, idiomatic,
and expected. You'd have to have a *really* good reason to use an
error value/code instead.
Python is not C, and despite what Joel has said On Software, error
codes generally suck.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: email notifier question ??

2008-11-13 Thread Chris Rebert
2008/11/13 yoma [EMAIL PROTECTED]:
 hi guys!
I want to use python send an email to acceptor.  And i hope to
 receive  the message that the acceptor has read my email.

 So how to realize that get the message?

To send an email using Python, you'll need to use the `smtplib`
module: http://docs.python.org/library/smtplib.html#module-smtplib

You'll have to check the relevant standards/specs related to email for
how to request a return receipt from the recipient in the message you
send.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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

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


Re: Sort dictionary by value when value is a list

2008-11-14 Thread Chris Rebert
On Fri, Nov 14, 2008 at 10:26 AM, major-john [EMAIL PROTECTED] wrote:
 I'm having trouble sorting a dictionary based on values when the values are
 all lists, and i want to sort the list by key with the largest value lists
 in decreasing size.

 Currently, I have the following:

 from operator import itemgetter

 dict = {'A': [(10, 20), (12, 18), (5, 11), (18, 25)], 'C': [(1, 200)], 'B':
 [(1, 10), (100, 200), (150, 300), (250, 350), (300, 400)], 'D': [(3, 400)]}

 I have tried several methods, and seem to have come closest using:

 sorted(self.dict.items(), key=itemgetter(1), reverse=True)

 My problem is that this will return the key order A,D,C,B
 The order I want is based on the size of the lists each key points to:
 B,A,D,C or B,A,C,D

 Question:
 itemgetter(1) is just returning the value, which is a list.  How do I
 specify that I want the values to be sorted by list size?

You just need to add a call to len() in the key function:

sorted(self.dict.items(), key=lambda pair: len(pair[1]), reverse=True)

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks!
 john





 --
 We are healthy only to the extent that our ideas are humane. --Killgore
 Trout

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


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


Re: Unsubscriptable object when using Exec

2008-11-14 Thread Chris Rebert
On Fri, Nov 14, 2008 at 10:40 AM, Indian [EMAIL PROTECTED] wrote:
 Hi Friends

 I'm getting the TypeError Unsubscriptable object when using Exec in a class

 Here's the example

 class Fake(object):
   def __init__(self, reg):
 self._reg = reg

   def OpenKey(self, rootkey, path):
 open_key = self._reg
 path_string='[\'HKLM\']'
 for key in path.split('\\'):
   path_string += '[\'%s\']'%key
 a='d=open_key%s'%path_string
 exec(a)
 return d

 When i create a claassobject and call the method Openkey i get the above
 error but it works fine in the below example without class

 def OpenKey(rootkey, path, reg):
   open_key = reg
   path_string='[\'HKLM\']'
   for key in path.split('\\'):
 path_string += '[\'%s\']'%key
   a='d=open_key%s'%path_string
   print a
   exec(a)
   return d

You don't need and shouldn't be using `exec` here. It appears as
though you're just doing the following in a much more obtuse and
unnecessarily complicated manner:

def OpenKey(rootkey, path, reg):
open_key = reg['HKLM']
for key in path.split('\\'):
open_key = open_key[key]
return open_key

Lesson: Don't use `exec`.
More importantly, what led you to think you needed to use it here in
the first place?

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 What am i doing wrong in the class?Any thought on this would be helpful :)

 Thanks in Advance

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

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


Re: Need help in understanding a python code

2008-11-15 Thread Chris Rebert
On Sat, Nov 15, 2008 at 8:41 PM, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 Hi,

 I am trying to understand the following line:
 # a is an integer array

 max([(sum(a[j:i]), (j,i))

This code isn't valid. You have a [ with no closing ].

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Can you please tell me what that means,
 I think sum(a[j:i] means find the some from a[j] to a[i]
 But what is the meaning of the part (j,i)?

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

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


Re: Customizing sequence types

2008-11-16 Thread Chris Rebert
On Sun, Nov 16, 2008 at 8:16 AM, Mr. SpOOn [EMAIL PROTECTED] wrote:
 Hi,
 I'm trying to create a class which inherit a list to change some behavior.
 This list should contain other instance objects and has to manage
 these instances in a particular way.

 1) I need to sort this elements in this list, but they must be sorted
 using an instance variable. What does Python use to sort elements? I
 mean, there is a __sort__ method in the class list or it just uses
 comparison operators? In this case, shall I just redefine this
 operators in the element classes?

It uses the comparison operators. IIRC, at a minimum it needs __lt__
and __eq__ to be defined on the elements.


 2) I need to have just unique elements. Maybe this is related to first
 question (or maybe not). Again, to estabilish the uniqueness of an
 element I have to use an instance variable. I think I have to rewrite
 both the methods append() and __contains__(), but I'm not sure how.

 For the first one I did:

def append(self, element):
if element in self:
pass
else:
list.append(self, element)

You should probably use the `bisect` module
(http://docs.python.org/library/bisect.html) for searching and
inserting into the list as it takes advantage of and ensures that the
list keeps sorted. It also means that __contains__ and some other
operations become O(log N) rather than O(N).

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 It seems right to me, but I have no idea what to do with __contains__()

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

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


Re: Optional parameter object re-used when instantiating multiple objects

2008-11-16 Thread Chris Rebert
On Sun, Nov 16, 2008 at 11:02 AM, George Sakkis [EMAIL PROTECTED] wrote:
 On Nov 16, 8:28 am, Steve Holden [EMAIL PROTECTED] wrote:

  +1. Understanding and accepting the current behavior (mainly because
  of the extra performance penalty of evaluating the default expressions
  on every call would incur) is one thing, claiming that it is somehow
  natural is plain silly, as dozens of threads keep showing time and
  time again. For better or for worse the current semantics will
  probably stay forever but I wish Python grows at least a syntax to
  make the expected semantics easier to express, something like:

  def foo(bar=`[]`):
  bar.append(6)

  where `expr` would mean evaluate the expression in the function
  body. Apart from the obvious usage for mutable objects, an added
  benefit would be to have default arguments that depend on previous
  arguments:

 Would you also retain the context surrounding the function declaration
 so it's obvious how it will be evaluated, or would you limit the default
 values to expressions with no bound variables?

 No, all expressions would be allowed, and the semantics would be
 identical to evaluating them in the function body; not context would
 be necessary.

  def foo(x, y=`x*x`, z=`x+y`):
  return x+y+z

  as opposed to the more verbose and less obvious current hack:

  def foo(x, y=None, z=None):
  if y is None: y = x*x
  if z is None: z = x+y
  return x+y+z

 Less obvious is entirely in the mind of the reader.

 Without documentation or peeking into the function body, a None
 default conveys little or no information, so I don't think it's just
 in the mind of the reader. Do you find the following less obvious than
 the current workaround ?

 from datetime import date
 from timedelta import timedelta

 def make_reservation(customer,
 checkin=`date.today()`,
 checkout=`checkin+timedelta(days=3)`):
   ...


 However I can see
 far more justification for the behavior Python currently exhibits than
 the semantic time-bomb you are proposing.

 I didn't propose replacing the current behavior (that would cause way
 too much breakage), only adding a new syntax which is now invalid, so
 one would have to specify it explicitly.

Minor FYI, but Guido has proscribed backticks ever being used in
Python again. See http://www.python.org/dev/peps/pep-3099/

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: Optional parameter object re-used when instantiating multiple objects

2008-11-16 Thread Chris Rebert
For the Nth time this year that this has come up, I'll point out yet
again that this issue has already been discussed to death before:

[Python-ideas] proto-PEP: Fixing Non-constant Default Arguments
http://mail.python.org/pipermail/python-ideas/2007-January/000121.html

[Python-3000] pre-PEP: Default Argument Expressions
http://mail.python.org/pipermail/python-3000/2007-February/005704.html

Result: Evaluating the arguments at runtime rather than
definition-time was deemed too magical; the backward compatibility
issues make changes unlikely; it's hard to find an acceptable syntax.

But hey, if some people want to have another go at it, best of luck.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


On Sun, Nov 16, 2008 at 8:11 PM, alex23 [EMAIL PROTECTED] wrote:
 On Nov 17, 12:27 pm, Steve Holden [EMAIL PROTECTED] wrote:
 If multiple statements are needed to perform the
 argument initialization, how would you then propose the problem should
 be solved?

 Why, with another function of course!

 def f(x, y=`f_arg_computation(x)`): ...

 Or my personal favourite:

 def f(x, **`f_arg_computation(x)`): ...

 Seriously, though, I agree with Steve; the function body -is- the
 place for computation to occur.
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Python and Its Libraries--Who's on First?

2008-11-17 Thread Chris Rebert
On Sun, Nov 16, 2008 at 9:25 PM, W. eWatson [EMAIL PROTECTED] wrote:
 Is there some repository that says something like for Python 2.5 it works
 with:

 Win OSes: W2K, XP, Vista

For the supported OSes, check the links for the versions on
http://python.org/download/ and see whether downloads are offered for
that OS (version).

 numpy vers y, matplotlib vers x. scipy z, etc.

For arbitrary third-party packages, check their websites to see which
versions are compatible with which versions of Python.

No one makes some centralized compatibility matrix for the cartesian
product of python, OS, and third-party library versions.
Probably because, as you can imagine, it would be enormously tedious.
Also, I doubt it would even be all that useful to most developers as
they simply go with whatever version of Python their package's
specific third-party libraries require, with OS compatibility being a
non-issue.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 --
   W. eWatson

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7 N, 121° 2' 32 W, 2700 feet

Web Page: www.speckledwithstars.net/

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

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


Re: Sorting lists

2008-11-17 Thread Chris Rebert
On Mon, Nov 17, 2008 at 1:56 AM, asc [EMAIL PROTECTED] wrote:
 Hi all,
 I have a problem and I'm not sure whether sort() can help me.
 I understand that if I have a list; say L = ['b', 'c', 'a']
 I can use L.sort() and I will then have; L = ['a', 'b', 'c']

 But my problem is this. I have a list, that contains a number of
 embeded lists;
 e.g. L2 = [['something', 'bb'], ['somethingElse', 'cc'],
 ['anotherThing', 'aa']]
 Now I want to sort this list by the second item of each sublist. So
 the outcome I would like is;
 L2 = [['anotherThing', 'aa'], ['something', 'bb'], ['somethingElse',
 'cc']]

 Is there a way I can use sort for this? Or am I going to have write a
 custom function to sort this out?

You use the `key` argument to .sort():

L2.sort(key=lambda item: item[1])

This sorts L2 by the result of applying the `key` function to each of
the items. Behind the scenes, I believe it does a Schwartzian
transform.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: Best practise hierarchy for user-defined exceptions

2008-11-17 Thread Chris Rebert
On Mon, Nov 17, 2008 at 3:47 AM, Slaunger [EMAIL PROTECTED] wrote:
 Hi there,

 I am a newcomer to Pyhton coming from Java working on a relatively
 large Pyhton project with several packages and modules. To improve
 exception handling I would like to introduce some user-defined
 exceptions to distinguish between exceptions raised in self-written
 code as compared to std libray modules used there-in.

 Say, for instance I would like to define a MyParseError exception to
 indicate that something has gone wrong while parsing a byte string, a
 file, or while packing into or unpacking from a struct.Struct
 instance.

 Here is my stub-implemented idea on how to do it so far, which is
 inspired by how I would have done it in Java (but which may not be
 very Pythonic??):

 class MyException(Exception):

pass


The above class probably isn't necessary. You don't need to
overgeneralize this much.

 class MyStandardError(MyException, StandardError):

pass

Rename the previous class to just MyError in light of removing the other class.


 class MyParseError(MyStandardError, ValueError):

   pass

This technique is very Pythonic. Subclass from both the exception
class for your module and from a built-in one if there's an applicable
one.


 Some comments and questions

 1. The hierarchy is deliberately deep and maps to the std library such
 that it is easier to extend

Zen of Python: Flat is better than nested.
This is part of the reason I recommend removing the one class.

 2. The implementations are empty but can be extended with hook for
 logging, statistics, etc.

True of stubs in general...

 3. I use multiple inheritance in the two sub-classes. I have not tried
 that before. Is this A Good Thing or A Bad Thing to do?

Good in this case, just be careful to use super() if you override any methods.

 4. Which __xx__ methods would you normally implement for the user-
 defined exception classes? I was thinking of __str__, for example? Is
 there a recommended __str__ idiom to use for that?

You might override __init__ if you want to store additional
information about the cause of the exception (e.g. location of parse
error, name of the rule the error occurred in, etc).
The __str__ inherited from Exception is usually sufficient, but you
can override it if you want to. it's a judgement call IMHO.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: Customizing sequence types

2008-11-17 Thread Chris Rebert
On Mon, Nov 17, 2008 at 10:05 AM, Mr. SpOOn [EMAIL PROTECTED] wrote:
 It seems that I solved my main problem, but I still have some doubt.

 I'll make an example:

 class foo:
 ...def __init__(self, a):
 ...self.a = a
 ...
 f = foo(1)
 f2 = foo(2)
 f3 = foo(3)
 f1 = foo(1)
 s = set()
 s.add(f)
 s
 set([__main__.foo instance at 0x8311fac])
 s.add(f2)
 s.add(f3)
 s.add(f1)
 s
 set([__main__.foo instance at 0x831934c, __main__.foo instance at
 0x83191cc, __main__.foo instance at 0x8311fac, __main__.foo
 instance at 0x831932c])

 I want that f and f1, that have both self.a set to 1, look the same to
 the set, so that it doesn't add f1. In this case the instances looks
 all different, so it adds them all.

 I tried rewriting __hash__ and __cmp__ in the foo class, so that
 __hash__ simply returns self.a and __cmp__ return self.a == other.a

__cmp__ does rich comparisons and is supposed to return 0 for
equality, -1 if the object is less than the other, and 1 if it's
greater than the other. So, using == as its definition is broken as it
returns just a boolean. You'd want cmp(self.a, other.a) if you were
defining __cmp__. However, == obviously works fine for __eq__, hence
why switching to __eq__ fixed your problem.

Also, __hash__  should probably delegate and be defined as
hash(self.a) rather than just self.a itself.


 I thought this would work, but I was wrong.
 I had to rewrite __eq__ with the same code of __cmp__

 Why it doesn't work with __cmp__ or __hash__ ?

Probably on account of one of the above errors I explained.

Cheers,
Chris
-- 
I wonder if there's a Mrs. FoRk...

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

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


Re: Socket Programming and Data transer 'advice'

2008-11-17 Thread Chris Rebert
On Mon, Nov 17, 2008 at 10:42 AM, Abah Joseph [EMAIL PROTECTED] wrote:
 I am planning to develop School Database Management System that will run on
 Windows, Linux and Mac. The application will be Server/Client and GUI based.

Have you considered basing this off existing software for schools,
like one of the programs listed on
http://en.wikipedia.org/wiki/Learning_management_system ?


 Modules I intende to use are: Python socket module, wxPython for GUI, Open
 GL for image processing , email and so on.

 This is my first real python project and I really want to test myself with
 this application.

Sounds like one hell of a project. Are you sure you aren't
encountering the Second System Effect
(http://en.wikipedia.org/wiki/Second-system_effect) despite this being
only your first project?


 Some planned features is:-

 SERVER
 Manage Client connections
 Handling Student/User registration
 Handling backup
 will also act as IM server (that will allow users to chat sometime)

Jabber a.k.a. XMPP (http://www.jabber.org/web/Main_Page) would
probably be a good option for IM.


 CLIENT
 Connect to sever
 Act as IM client
 Retrieve data from server.

 I will not be able to list all features.

 My Question is:

 What is the best database to use? (Flat file, cPickle, MySql, Sqlite,XML
 etc)

MySQL or Sqlite, probably the former. The other ones you list aren't
really databases per se.


 Security to make sure data is safe

Use some kind of encryption; I'd recommend using KeyCzar -
http://www.keyczar.org/


 How are binary data transferred from location x to y?, and during the
 transferring what should happen if not fully transferred and assume power
 goes off. Start all over again or continue?

 What is the secret behind transparent file transfer like the one in Yahoo IM
 (I can see what i`m transferring to you, u as well).

Don't really know what you mean by this.


 Audio streaming.

IceCast might be a good starting point - http://www.icecast.org/


 My intension here is to know what to do or read more and not asking you to
 write code for me

 Just your advice.

Good luck. Sounds like an ambitious project. Hope the pointers I gave help.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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


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


Re: How to deal with globals during refactoring classes into separate files.

2008-11-18 Thread Chris Rebert
On Tue, Nov 18, 2008 at 4:14 PM, r0g [EMAIL PROTECTED] wrote:
 Hi There,

 I'm refactoring some old code that uses global variables and was
 originally written in one big flat file with a view to nicening it up
 and then extending it. The problem I have though is when I move the
 various classes out to their own separate files and reimport them back
 in they can't see the globals in the main program. Most of the globals
 were just constants and so I have been able to factor them out but
 there's one that's kind of pivotal that I still need, basically a list
 of all the threads I have running, I don't see how I could get rid of
 that. Example follows...

 The original with global variable and classes all in one file...

 dirty_global = whatever
 class example():
  def print_message(self):
print Sure, +dirty_global
 a = example()
 a.print_message()

Sure, whatever


 But when I put the class in  its own file and then import it back in...


 from example_class import example
 dirty_global = whatever
 a = example()
 a.p()

NameError: global name 'dirty_global' is not defined



 I had thought declaring the variable using the global keyword at the top
 of the file might make it a global 'proper' (as per the manual) or that
 using it at the top of the class file might somehow allow the class to
 see the variable in file it was called from but clearly my understanding
 of python namespaces and scoping isn't quite there yet as neither of
 these seem to make any difference.

A `global` declaration at the module-level, while syntactically valid,
doesn't do anything. It only really makes sense to use `global` in
function bodies.
And as Gabriel explained, Python has no program-wide global scope.
Global scope is always module-specific.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 How can get my classes to see this 'dirty_global' variable again?

 Thanks,

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

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


Re: Exception difference 2.4 == 2.5

2008-11-18 Thread Chris Rebert
On Tue, Nov 18, 2008 at 8:56 PM, D'Arcy J.M. Cain [EMAIL PROTECTED] wrote:
 I am having a strange problem and I can't seem to zero in on it.  I am
 also having trouble reducing it to a small enough snippet that I can
 post here.  I think that I am doing what the more complex script does
 but none of my attempts fail.  So, here is a description just in case
 someone has seen something that smells like this and can suggest some
 areas to do further poking.

 I have a class that subclasses xmlrpcserver.RequestHandler.  It has a
 method that takes a function name that it looks up with getattr.  It
 then calls the looked up method in this try/except block:

try:
return server_method(pkt)
except Exception, failure:
syslog(LOG_WARNING, %s, %s % (Exception, failure))
self.print_tb(sys.exc_info())

try: fault = self.faultConverter.errorToFault(failure)
except Exception, err:
syslog(LOG_ERR, Error processing failure: %r % err)
fault = xmlrpclib.Fault(8002, Internal error)

syslog(LOG_DEBUG, Converted failure %r to fault %r (%r) %
 \ (failure, fault, failure))

if fault.faultCode  1:
syslog(LOG_ERR, Unconverted fault: %r % failure)

return fault

 This class is then subclassed by another class that adds the methods
 that are to be looked up.  Those methods may raise exceptions if there
 are errors.

 Under Python 2.4 this works fine.  If an exception is raised in the
 looked up method it gets handled by this code just fine.  Under 2.5,
 however, the exception is not caught here.  It's as if there was no
 try/except here at all.

What happens under Python 2.6?

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 I'm not sure if I have left off some critical piece of information or
 just littered this post with red herrings.  I'm open to both
 reasoned suggestions as well as wild speculation.

 --
 D'Arcy J.M. Cain [EMAIL PROTECTED] |  Democracy is three wolves
 http://www.druid.net/darcy/|  and a sheep voting on
 +1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Non blocking socket server and storage engine

2008-11-19 Thread Chris Rebert
On Wed, Nov 19, 2008 at 2:36 AM, kdeveloper
[EMAIL PROTECTED] wrote:
 Hello Pythonists,

 I am building a non blocking socket server for incomming UDP packets.
 The server needs to run at least three threads:
 1. getting data and pushing to some storage (at the moment I use
 queue),
 2. acknowledge the package received
 3. retrieve the information from the storage and insert it in DB.

 The problem I have is that when I use queue it stores more packets in
 the queue than it actually receives. An example: sent 99 UDP packets
 and queue stored 600-750 entries (?) Why? I have no idea. I have
 impression that I still do not understand completely how does the
 queue work in python.

No, I believe rather you don't completely understand UDP.

Quoting from Wikipedia (http://en.wikipedia.org/wiki/User_Datagram_Protocol):
UDP does not guarantee reliability or ordering in the way that TCP
does. Datagrams may arrive out of order, ***appear duplicated***, or
go missing without notice.

I think that might at least partially account for your duplicate entries.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Another issue is that I want the server to run very rupidly. The
 server needs to get at least 100 packets per second, and the same
 amount of acknowledges has to be sent back.

 The questions are:
 1. What is the best storage engine for Python and multithreading
 server?
 2. Can I use queue for such problem?
 3. How does actually queue work in Python? (I know how it should work
 generally, but somehow it doesn't work as I expect)

 Any hints  helps? Would be very grateful

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

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


Re: Exception difference 2.4 == 2.5

2008-11-19 Thread Chris Rebert
On Wed, Nov 19, 2008 at 8:24 AM, D'Arcy J.M. Cain [EMAIL PROTECTED] wrote:
 On Tue, 18 Nov 2008 22:33:35 -0800
 Chris Rebert [EMAIL PROTECTED] wrote:
 What happens under Python 2.6?

 Interesting.  I installed 2.6 and tried it.  My unit test still failed
 but for a different reason that I will have to investigate but the
 exceptions were handled correctly.  Does this suggest something to you?

I would wildly guess that you might have encountered a bug in Python
that was since fixed. Hard to be sure though.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 --
 D'Arcy J.M. Cain [EMAIL PROTECTED] |  Democracy is three wolves
 http://www.druid.net/darcy/|  and a sheep voting on
 +1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.

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


Re: Getting fractional part from a float without using string operations

2008-11-19 Thread Chris Rebert
On Wed, Nov 19, 2008 at 10:01 PM, srinivasan srinivas
[EMAIL PROTECTED] wrote:
 Yes it works for most of the cases.  But it doesn't for the following case:

 str(abs(int(1234567.89)-1234567.89))
 '0.88999898'

Since you really care about significant figures here, have you
considered using decimal rather than float as, IIRC, it handles this
correctly?

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks,
 Srini


 - Original Message 
 From: Tino Wildenhain [EMAIL PROTECTED]
 To: srinivasan srinivas [EMAIL PROTECTED]
 Cc: Jeremiah Dodds [EMAIL PROTECTED]; python-list@python.org
 Sent: Wednesday, 19 November, 2008 7:33:46 PM
 Subject: Re: Getting fractional part from a float without using string 
 operations

 srinivasan srinivas wrote:
 Yes. But it didn't give only the expected decimals.
 For ex:
   a = 1.23
   abs(int(a) -a)
 0.22998
  I would like to get the result '0.23' only.

 well, thats what get stored internally - there
 is no way around it if you are using floating
 point numbers:

 0.23
 0.23001

 but str() handles the rounding correctly:

 print 0.23
 0.23

 print abs(int(a) -a)
 0.23

 See also http://en.wikipedia.org/wiki/Floating_point
 for the problems with FP figures.

 Regards
 Tino



  Get perfect Email ID for your Resume. Grab now 
 http://in.promos.yahoo.com/address
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Two functionaly identical functions - different results ??!

2008-11-19 Thread Chris Rebert
On Wed, Nov 19, 2008 at 11:24 PM, Barak, Ron [EMAIL PROTECTED] wrote:
 Hi Guys,

 I cannot see any difference between read1() and read2() below, and yet, one
 is okay, the other give an exception.

 In the first run, read2() is executed, and as expected, the text file is
 printed

 $ cat ./gzip_try.py
 import gzip

 FILE = text_file.txt

 def read2():
 try:
 fl = gzip.GzipFile(FILE, r)
 print fl.read()
 except IOError:
 fl = open(FILE, r)
 print fl.read()

 def read1():
 try:
 fl = gzip.GzipFile(FILE, r)
 except IOError:
 fl = open(FILE, r)

 print fl.read()

 read2()
 #read1()

 $ python ./gzip_try.py
 abc
 123

 In the second run, read1() is executed, and an IOError: Not a gzipped file
 exception is thrown from the print fl.read() line of read1().
 This is baffling to me, as the try...except should have established that the
 file is a text and not gzip file !

 $ cat ./gzip_try.py
 import gzip

 FILE = text_file.txt

 def read2():
 try:
 fl = gzip.GzipFile(FILE, r)
 print fl.read()
 except IOError:
 fl = open(FILE, r)
 print fl.read()

 def read1():
 try:
 fl = gzip.GzipFile(FILE, r)
 except IOError:
 fl = open(FILE, r)

 print fl.read()

 #read2()
 read1()

 $ python ./gzip_try.py
 Traceback (most recent call last):
   File ./gzip_try.py, line 22, in module
 read1()
   File ./gzip_try.py, line 19, in read1
 print fl.read()
   File c:\Python25\lib\gzip.py, line 220, in read
 self._read(readsize)
   File c:\Python25\lib\gzip.py, line 263, in _read
 self._read_gzip_header()
   File c:\Python25\lib\gzip.py, line 164, in _read_gzip_header
 raise IOError, 'Not a gzipped file'
 IOError: Not a gzipped file

 $

 Can anyone explain why read1() throws an exception, while read2() behaves
 correctly ?

As I believe someone else pointed out recently in a extremely similar
thread, GzipFile apparently doesn't check that the underlying file is
actually in gzip format until the .read() call, hence why its
placement affects where the exception is thrown and thus how it's
handled. read2() has the .read() for the gzipped case within the
`try`, so the exception, if it's going to get thrown, is thrown there
and handled by the except. In contrast, read1() has the .read() call
outside the `try` and so the possible exception doesn't get caught.
IOW, putting the GzipFile() creation in a `try` is pointless in this
case as .read(), and not the initialization, throws the exception.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks,
 Ron.

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


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


Re: Using eval, or something like it...

2008-11-20 Thread Chris Rebert
On Thu, Nov 20, 2008 at 3:54 PM, r0g [EMAIL PROTECTED] wrote:
 Scott David Daniels wrote:
 r0g wrote:
 John Machin wrote:
  You mention variables of a class but you then proceed to poke
 at an instance of the class
 Check out setattr (and getattr) in the docs.
 The former i.e. the variables of an instance of a class. Thanks :-)

 Careful here.  Your wording seems to indicate you misunderstand the
 Python model.  The instance doesn't have variables (and your class built
 nothing that could be called an instance variable).  Think of the
 attributes of an instance (or a class) as values attached to (or
 associated with) the instance.  If you don't you are setting yourself
 up to discover a pile of bugs that you don't understand.

 --Scott David Daniels
 [EMAIL PROTECTED]


 OK now I'm confused, let me explain how I see things at the moment and
 you can correct me...

 A class is like a template which combines a complex data type (made from
 a combination of other data types) and the methods that operate on that
 data type.

 You generally don't work with classes directly but you make instances of
 them, each instance has it's own internal state and methods, initially
 these are the same as the templates but can be changed or overridden
 without affecting the state of any other instances you might have.

 While the perceived wisdom is that you should encapsulate all the
 methods you need to modify your classes' state within the class itself
 Python does (for better or worse) permit you to reach inside a class and
 futz with it's state directly from outside.

 The bits of an instance's state one might futz with (from within or
 without) i.e. the primitives that make up the complex object the class
 is a representation of, I think of as it's variables.

 It would seem from this setattr function that the proper term for these
 is 'attributes'. That for many years I have considered pretty much any
 named thing that may vary a 'variable' might be at the root of the
 problem here as it's a very un-specific term...

 So I gather you are saying that the fragments of state within a class
Within an instance
 are so distinct from ordinary common or garden variables that it is
 incorrect to think of them, or describe them, as variables, much like
 quarks should not really be regarded as distinct particles, and they
 should only be thought of and described as 'attributes' to avoid confusion?

 Is this correct enough for me to avoid the aforementioned bug pile?

Yes, I think so.


 Also then, what _is_ an instance variable ?

Metasyntatic variables:
  C - some class
  x - some instance
  y - the word after the dot in the expression: x.y


My working definitions based on my knowledge of Python:

Attribute - y is an attribute of x. Includes instance variables,
properties, and dynamically generated attributes. Since x.y really
ends up doing x.__getattribute__(y) behind the scenes, overriding
__getattribute__ lets you make attribute lookup more dynamic and have
it do interesting things. For example, you could write a class
overriding __getattribute__ so that x.y (for any valid Python name y)
opened a file with the name y and returned a file object for this file
(i.e. x.z returns file(z,w), x.q returns file(q,w), etc
without enumerating q, z, etc anywhere in the class).

Instance variable - In `x.y`, y is an instance variable of x if it's
stored in x.__dict__ or x.__slots__, it's not a method of x (though it
can be a function), and it's not a property.

Property - y is a property if x.y causes a method call and returns the
result of said method call. Basically, x.y becomes equivalent to x.z()
if y is a property. Properties can also allow `x.y = a` to be
equivalent to `x.z(a)` and `del x.y` to be equivalent to `x.z()`.
Properties are created using the built-in function property()

Class variable - Unless you're using metaclasses, in C.y, y is always
a class variable of C. Thus, methods are technically also class
variables. Using metaclasses, C is both a class itself and an instance
of another class D, in which case the definition of instance
variable (interpreted with regards to C being an instance of D)
applies to whether y is a class variable of C or not.

Class method - Created using the built-in function classmethod()

Essentially, attribute lookup is very dynamic in Python, which
complicates things a good bit, so the only thing we know for sure
about x.y is that y is an attribute of x.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks,


 Roger.

 Q: How many pedants does it take to change a lightbulb?
 A: Well actually you mean replace a lightbulb.
 Q: Have you ever kissed a girl?
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Sending username password to a webpage

2008-11-20 Thread Chris Rebert
On Thu, Nov 20, 2008 at 7:52 PM, KDawg44 [EMAIL PROTECTED] wrote:
 Hi,

 Is there a way to essentially simulate populating a text box and
 calling a submit button on a webpage?  I want to write an app that
 gets a users information from a website and then uses that to get
 information from another site.  The first site requires a log in.

There's the mechanize library for programmatic web browsing:
http://wwwsearch.sourceforge.net/mechanize/

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks for any advice that gets me in the right direction.

 Thanks.

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

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


<    1   2   3   4   5   6   7   8   9   10   >