UR SCHOOL AND COLLEGE'S, PLEASE REGISTER UR SCHOOL AND COLLEGE NAME'S IN THIS SITE. "" IF U HAVE TIME THEN DO IT. PLEASE I REQUEST. """

2008-06-06 Thread jack
IF you want to meet your old school mate's & college mate's of your
life there is a chance, just enter school or college details in the
below site

http://www.batchmates.com/institution/regform.asp?refid=1529710&reflink=31481

please forward to ur friend's
tell to them forward this message to there friend's
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to kill a thread?

2008-06-06 Thread Rhamphoryncus
On Jun 6, 12:44 pm, The Pythonista <[EMAIL PROTECTED]> wrote:
> It's always been my understanding that you can't forcibly kill a thread
> in Python (at least not in a portable way).  The best you can do is
> politely ask it to die, IIRC.

Inherently, the best you can do in most languages is ask them politely
to die.  Otherwise you'll leave locks and various other datastructures
in an inconvenient state, which is too complex to handle correctly.
The exception is certain functional languages, which aren't capable of
having threads and complex state in the same sense.

However, you could go quite far with a standardized mechanism of
politely asking threads to die.  For instance, all blocking I/O
functions could be made to support it.  This is how cancellation works
in python-safethread.
--
http://mail.python.org/mailman/listinfo/python-list


100 Tools For Blogging

2008-06-06 Thread GoodieMan
Whether you're a seasoned blogger wanting to increase your blog
traffic or a novice looking for advice on where to begin, these
resources [ http://100tools4blogs.blogspot.com/ ] can offer great help
getting you on the right track. Use them wisely and you can increase
your chances of creating a successful and interesting blog, and maybe
even becoming an online sensation. http://100tools4blogs.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Needing python experts to help with a problem

2008-06-06 Thread John Nagle

CM wrote:

On Jun 7, 12:51 am, gms <[EMAIL PROTECTED]> wrote:

Hello,
I have the following list:

[{'count': u'2', 'manu': }, {'count': u'4',
'manu': }, {'count': u'2', 'manu': }, {'count': u'2', 'manu': }]

...

This sounds like a homework assignment.  If you're having trouble
with this, sending mail from Python is really going to be a headache
for you.

You want something like

inlist = [{'count': u'2', 'manu': }, {'count': u'4',
> 'manu': }, {'count': u'2', 'manu':  Manu3>}, {'count': u'2', 'manu': }]

outdict = {}
for mandict in inlist :
if not outdict.has_key(mandict[manu])   # if first for this manu
outdict[mandict[manu]] = [] # make empty list
outdict[mandict[manu]].append(mandict)  # append entry to list  

You now have the desired result in a dictionary, which you can convert to a list
if you like.

If it's a production job, and the number of manufacturers is large,
you're probably better off using a database like MySQL, or some
mail merge program.

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


Parsing a path to components

2008-06-06 Thread eliben
Hello,

os.path.split returns the head and tail of a path, but what if I want
to have all the components ? I could not find a portable way to do
this in the standard library, so I've concocted the following
function. It uses os.path.split to be portable, at the expense of
efficiency.

--
def parse_path(path):
""" Parses a path to its components.

Example:
parse_path("C:\\Python25\\lib\\site-packages\
\zipextimporter.py")

Returns:
['C:\\', 'Python25', 'lib', 'site-packages',
'zipextimporter.py']

This function uses os.path.split in an attempt to be portable.
It costs in performance.
"""
lst = []

while 1:
head, tail = os.path.split(path)

if tail == '':
if head != '': lst.insert(0, head)
break
else:
lst.insert(0, tail)
path = head

return lst
--

Did I miss something and there is a way to do this standardly ?
Is this function valid, or will there be cases that will confuse it ?

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


Re: Macro like functionality for shorthand variable names

2008-06-06 Thread Kay Schluehr
On 6 Jun., 23:13, Tilman  Kispersky <[EMAIL PROTECTED]> wrote:
> I have python code in a class method translated from C++ that looks
> sort of like this:
>
> >>>  self.dydt[1] = self.a * (self.b * self.y[0] - self.y[1])
>
> To make this more readable in C++ I had made macros to achieve this:
> #define du (dydt[1])
> #define u (y[1])
> #define V (y[0])
>
> du = a * (b * V - u);
>
> I realize the value of not having macros in Python.  They've tripped
> me up more than once in C++.  My question is:
> Is there any way to write a shorterhand more readable version of the
> python code above?  I'm doing several calculations one after the other
> and some of the lines are quite long.

There is no entirely generic way but you can define a function that
produces a string from an object that contains assignments and then
use exec:

def tovars(obj):
return ";".join("%s=%s"%(n,v) for (n,v) in obj.__dict__.items())

# example

class A:pass

>>> a = A()
>>> a.x = 0
>>> a.y = 1
>>> exec tovars(a)
>>> y
1
>>> x
0

In your own case the tovars) function might be defined as:

def tovars(obj):
assign = []
assign.append("du = %s"%obj.dydt[1])
assign.append("u = %s"%obj.y[1])
assign.append("V = %s"%obj.y[0])
return ";".assign



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


Re: Needing python experts to help with a problem

2008-06-06 Thread CM
On Jun 7, 12:51 am, gms <[EMAIL PROTECTED]> wrote:
> Hello,
> I have the following list:
>
> [{'count': u'2', 'manu': }, {'count': u'4',
> 'manu': }, {'count': u'2', 'manu':  Manu3>}, {'count': u'2', 'manu': }]
>
> My current list currently contains four dictionaries.  They are:
>
> {'count': u'2', 'manu': }
> {'count': u'4', 'manu': }
> {'count': u'2', 'manu': }
> {'count': u'2', 'manu': }
>
> I need to create a list for each specific Manufacturer.  Since I have
> two dictionaries that have 'Manu2' as it's manufacturer.  I will need
> some code that will create the following from the list above:
>
> [{'count': u'2', 'manu': }]
> [{'count': u'4', 'manu': },{'count': u'2',
> 'manu': }]
> [{'count': u'2', 'manu': }]
>
> The reason for this is because I want to send one email to each
> manufacturer.  In this case I would send two emails to Manu2 because I
> have two dictionaries that have Manu2 as the manufacturer.  That is
> why I need to create a separate list for each manufacturer.
>
> Any help on on how best to do this would be greatly appreciated!
>
> Thanks

I'm not expert, but it just seems that this structure is overly
complex.  What is your goal, and what information do you want to
associate with each manufacturer?  Couldn't you simplify this
this section:

> {'count': u'2', 'manu': }
> {'count': u'4', 'manu': }
> {'count': u'2', 'manu': }
> {'count': u'2', 'manu': }

to something like:

manu_dict = { Manu1:[2], Manu2:[4,2], Manu3:[2] }

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


Re: Do this as a list comprehension?

2008-06-06 Thread Mensanator
On Jun 6, 10:33 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Mensanator" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> On Jun 6, 1:44 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > "Mensanator" <[EMAIL PROTECTED]> wrote in message
>
> >news:[EMAIL PROTECTED]
> > | On Jun 5, 10:42?pm, John Salerno <[EMAIL PROTECTED]> wrote:
> > | > Is it possible to write a list comprehension for this so as to
> > produce
> > a
> > | > list of two-item tuples?
> > | >
> > | > base_scores = range(8, 19)
> > | > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]
> > | > print zip(base_scores, score_costs)
> > | >
> > | > I can't think of how the structure of the list comprehension would
> > work
> > | > in this case, because it seems to require iteration over two separate
> > | > sequences to produce each item in the tuple.
>
> > Which is exactly the purpose of zip, or its specialization enumerate!
>
> Aren't you overlooking the fact that zip() truncates the output
> to the shorter length iterable?
> =
> 
>  No.
> =
> And since the OP foolishly
> hardcoded his range bounds, zip(base_scores,score_cost) will
> silently return the wrong answer if the base_count list grows.
> 
>  So, to future proof his code he should better use
> zip(itertools.count(8), score_costs).  I consider this better than using
> enumerate to make the wrong pairing (with itertools.count(0)) and then
> correcting the mistake.

Mistake? How is starting at 0 a mistake? Because .count() can
start at 8, eliminating the i+8 construction? But what if
I wanted to count by two or want a sequence cubes that start
at 8? Can itertools do that? I would say knowing how to
manipulate a 0-based iterable will pay off more in the long
run. If you don't know how to get the index numbers you want
from enumerate(), itertools isn't going to help.

> 
> Surely enumerate() wasn't added to Python with no intention of
> ever being used.
> 
>  Of course not, so why suggest that is was?
> However, it was intended for the most common case when one wants to pair
> items with counts beginning with 0.
> =
>
> > Of course, enumerate(iterable) is just a facade over
> > zip(itertools.count(),
> > iterable)
>
> But if all I'm using itertools for is the count() function, why would
> I go to the trouble of importing it when I can simply use enumerate()?
> 
> I have no idea.  The purpose of enumerate is to be easy.
> But it is not so easy when it gives the wrong pairings.

The same can be said of zip() if you're not careful
about the size of the iterables. There is no substitute
for understanding how things work.

> ===
> Is it a couple orders of magnitude faster?
> =
>  Perhaps you do not understand 'facade' - the front part or face of
> something that you see.  

Well, I also understand the secondary meaning:
2. An artificial or deceptive front

> I was saying that enumerate is a face on a room
> containing zip and itertools.count, or the equivalent code thereof.

I thought you were trying to imply that to use enumerate()
is to be un-Pythonic, that _real_ programmers always use
itertools.

> Therefore, enumerate is an easy way to do a particular zip, not an
> alternative to zip.  

Ok, I mistook your use of 'facade' for arrogance,
just as the OP mistook my use of 'foolishly' for
arrogance. Ain't English wonderful?

> And there should be no significant performance
> difference, certainly for long sequences which make the additional lookups
> irrelevant.
>
> tjr
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to send a POST request?

2008-06-06 Thread subeen
On Jun 7, 6:17 am, "Jeff McNeil" <[EMAIL PROTECTED]> wrote:
> The original urllib module will do it too, if you pass a data keyword
> argument to urllib.urlopen:
>
> u = urllib.urlopen('http://www.domain.com/cgi-bin/cgi.py',
> data=urllib.urlencode({'name': 'pythonguy'}))
>
> On Fri, Jun 6, 2008 at 6:04 PM, kj <[EMAIL PROTECTED]> wrote:
> > In <[EMAIL PROTECTED]> kj <[EMAIL PROTECTED]> writes:
>
> >>Hi.  Sorry for this very clueless question, but how does one write
> >>in Python an HTTP client that can send a POST request?  The modules
> >>I've found (e.g. urllib, urllib2), as far as I can tell, seem to
> >>be limited to GET requests.  (I could be wrong though; please
> >>correct me if this is so.)
>
> > Sorry, my mistake.  I now see that urllib2 handles POSTs too.
>
> > kynn
>
> > --
> > NOTE: In my address everything before the first period is backwards;
> > and the last period, and everything after it, should be discarded.
> > --
> >http://mail.python.org/mailman/listinfo/python-list

check this link for http post:
http://love-python.blogspot.com/2008/04/get-content-html-source-of-url-by-http.html

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


Re: Dynamically naming objects.

2008-06-06 Thread stefaan.himpe

Hello,

You can use this as indicated by Hans:


   u = [user() for i in xrange(5)]


where "user" is a class or a function returning an object.
u then is a list of "user" objects.


or does it somehow work? how would I address them if they all have the
name 'u'?


You'd access members of the list as u[0], u[1], ... etc.
I think you'd benefit from reading an introductory programming book.

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


Re: Dynamically naming objects.

2008-06-06 Thread Alan Isaac
On Jun 7, 1:20 pm, Hans Nowak 

  [user() for i in range(n)]



Kalibr wrote:
or does it somehow work? how would I address them if they all have the 
name 'u'? 



users = list(User() for i in range(n))
for user in users:
   user.do_something()

hth,
Alan Isaac

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


Re: Dynamically naming objects.

2008-06-06 Thread Ben Finney
Kalibr <[EMAIL PROTECTED]> writes:

> what I want to do is have, say 5 users in a game, so I'd have to
> spawn 5 objects. I can't do that because I have'nt hardcoded any
> object names for them.

Python's built-in mapping type 'dict' is a good fit for this.

Given:

* a 'User' class that is initialised with the user's name

* some way of getting a sequence of names (that you haven't told us
  yet), that I'll bind here to the name 'sequence_of_names'

You can then write::

game_users = {}
for name in sequence_of_names:
game_users[name] = User(name)

This will result in 'game_users' bound to a dict with names mapping to
separate instances of the 'User' type. These instances can each be
addressed by name from the 'game_users' mapping as
'game_users["Fred"]', etc.

-- 
 \   "Pinky, are you pondering what I'm pondering?" "Well, I think |
  `\  so, Brain, but do I really need two tongues?"  -- _Pinky and |
_o__)   The Brain_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Needing python experts to help with a problem

2008-06-06 Thread gms
Hello,
I have the following list:

[{'count': u'2', 'manu': }, {'count': u'4',
'manu': }, {'count': u'2', 'manu': }, {'count': u'2', 'manu': }]

My current list currently contains four dictionaries.  They are:

{'count': u'2', 'manu': }
{'count': u'4', 'manu': }
{'count': u'2', 'manu': }
{'count': u'2', 'manu': }

I need to create a list for each specific Manufacturer.  Since I have
two dictionaries that have 'Manu2' as it's manufacturer.  I will need
some code that will create the following from the list above:

[{'count': u'2', 'manu': }]
[{'count': u'4', 'manu': },{'count': u'2',
'manu': }]
[{'count': u'2', 'manu': }]

The reason for this is because I want to send one email to each
manufacturer.  In this case I would send two emails to Manu2 because I
have two dictionaries that have Manu2 as the manufacturer.  That is
why I need to create a separate list for each manufacturer.

Any help on on how best to do this would be greatly appreciated!

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


Professional Grant Proposal Writing Workshop (August 2008: Ann Arbor, Michigan - University of Phoenix Campus)

2008-06-06 Thread Anthony Jones


The Grant Institute's Grants 101: Professional Grant Proposal Writing Workshop
 will be held at the University of Phoenix - Ann Arbor Campus on August 20 - 22, 2008.  Interested development professionals, researchers, faculty, and graduate students should register as soon as possible, as demand means that seats will fill up quickly. Please forward, post, and distribute this e-mail to your colleagues and listservs. 
 
All participants will receive certification in professional grant writing from the Institute. For more information call (888) 824 - 4424 (213-817-5308 outside US) or visit The Grant Institute at www.thegrantinstitute.com.
 
Please find the program description below:
 
The Grant Institute
Grants 101: Professional Grant Proposal Writing Workshop
will be held at the 
University of Phoenix - Ann Arbor Campus
Ann Arbor, Michigan
August 20 - 22, 2008
8:00 AM - 5:00 PM
 

The Grant Institute's Grants 101 course is an intensive and detailed introduction to the process, structure, and skill of professional proposal writing. This course is characterized by its ability to act as a thorough overview, introduction, and refresher at the same time. In this course, participants will learn the entire proposal writing process and complete the course with a solid understanding of not only the ideal proposal structure, but a holistic understanding of the essential factors, 
which determine whether or not a program gets funded. Through the completion of interactive exercises and activities, participants will complement expert lectures by putting proven techniques into practice. This course is designed for both the beginner looking for a thorough introduction and the intermediate looking for a refresher course that will strengthen their grant acquisition skills. This class, simply put, is designed to get results by creating professional grant proposal writers. 

 
Participants will become competent program planning and proposal writing professionals after successful completion of the Grants 101 course. In three active and informative days, students will be exposed to the art of successful grant writing practices, and led on a journey that ends with a masterful grant proposal. 
 
Grants 101 consists of three (3) courses that will be completed during the three-day workshop. 
 
(1) Fundamentals of Program Planning
 
This course is centered on the belief that "it's all about the program." This intensive course will teach professional program development essentials and program evaluation. While most grant writing "workshops" treat program development and evaluation as separate from the writing of a proposal, this class will teach students the relationship between overall program planning and grant writing. 
 
(2) Professional Grant Writing
 

Designed for both the novice and experienced grant writer, this course will make each student an overall proposal writing specialist. In addition to teaching the basic components of a grant proposal, successful approaches, and the do's and don'ts of grant writing, this course is infused with expert principles that will lead to a mastery of the process. Strategy resides at the forefront of this course's intent to illustrate grant writing as an integrated, multidimensional, and dynamic endeavor. 
Each student will learn to stop writing the grant and to start writing the story. Ultimately, this class will illustrate how each component of the grant proposal represents an opportunity to use proven techniques for generating support.
 
(3) Grant Research
 

At its foundation, this course will address the basics of foundation, corporation, and government grant research. However, this course will teach a strategic funding research approach that encourages students to see research not as something they do before they write a proposal, but as an integrated part of the grant seeking process. Students will be exposed to online and database research tools, as well as publications and directories that contain information about foundation, corporation, and 
government grant opportunities. Focusing on funding sources and basic social science research, this course teaches students how to use research as part of a strategic grant acquisition effort.
 
Registration
$597.00 tuition includes all materials and certificates.
 
Each student will receive:
*The Grant Institute Certificate in Professional Grant Writing
*The Grant Institute's Guide to Successful Grant Writing
*The Grant Institute Grant Writer's Workbook with sample proposals, forms, and outlines
 
Registration Methods
 
1) On-Line - Complete the online registration form at www.thegrantinstitute.com under Register Now. We'll send your confirmation by e-mail. 
 
2) By Phone - Call (888) 824 - 4424 (213-817-5308 outside US) to register by phone. Our friendly Program Coordinators will be happy to assist you and answer your questions. 
 
3) By E-mail - Send an e-mail with your name, organization, and basic contact information to [EMAIL PROTECTED]

Re: Dynamically naming objects.

2008-06-06 Thread Kalibr
On Jun 7, 1:20 pm, Hans Nowak <[EMAIL PROTECTED]> wrote:
> Kalibr wrote:
> > I've been developing a small script to fiddle with classes, and came
> > accross the following problem. Assuming I get some user input asking
> > for a number, how would I spawn 'n' objects from a class?
>
> > i.e. I have a class class 'user' and I don't know how many of them I
> > want to spawn.
>
> > Any ideas?
>
> Sure. This will give you a list of n instances of user:
>
>[user() for i in range(n)]
>
> Of course, you could also use a good old for loop:
>
>for i in range(n):
>u = user()
>...do something with u...
>
> Hope this helps!
>
> --
> Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/

whoops, replied to author

What I wanted to ask before was won't 'u' be overwritten with a new
object each time the loop ticks over?

what I want to do is have, say 5 users in a game, so I'd have to spawn
5 objects. I can't do that because I have'nt hardcoded any object
names for them.

or does it somehow work? how would I address them if they all have the
name 'u'?
--
http://mail.python.org/mailman/listinfo/python-list


Re: ctypes help

2008-06-06 Thread Mark Tolonen


"gianluca" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

hy,
I've a huge problem with ctypes. I've compiled my C library and I'd
like use it in python with ctype. One function need to pass a pointer
to typed ( like this: typedef int value_type). In python I can access
to that funtion but arise an exception  because python don't know my
value_type typedef.

Please I need help, could anybody help me?

Gianluca


Let's see if I understand you correctly.  You have a typedef, and a function 
that is passed a pointer to that typedef.  Below is a short Windows DLL, 
compiled with "cl /LD example.c"


   typedef int value_type;

   __declspec(dllexport) void function(value_type* x)
   {
   *x *= 2;
   }

And here is some python code to call it:


from ctypes import *
value_type = c_int  # declares a type "value_type" 
as a ctypes integer

value=value_type(5)   # create an instance of value_type
function=cdll.example.function  # look up the function and declare 
return type and arguments

function.restype=None
function.argtypes=[POINTER(value_type)]
function(pointer(value))  # call the function with a pointer 
to the instance

value

c_long(10)

Hope that helps.
-Mark

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


Re: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket

2008-06-06 Thread Nir
Can you check another hypothesis?

I currently do not have a Python installation to verify this but if my
memory does not fail me there is a DLL library somewhere under c:
\python25 and _socket might be there as well. Copy any DLLs you find
there to the same folder as your embedded interpreter DLL and see if
the problem is resolved.

Nir


On Jun 6, 11:25 am, [EMAIL PROTECTED] wrote:
> On Jun 6, 1:13 am, Nir <[EMAIL PROTECTED]> wrote:
>
>
>
> > You seem to be having a problem with the import path of the embedded
> > interpreter. I suppose the embedded interpreter includes some modules
> > in a particular folder and _socket is not one of them. For the sake of
> > debugging try adding the c:\python25\lib path to the sys.path variable
> > of the interpreter before attempting to import rpdb2.
>
> > Does this work?
>
> > Nir
>
> > On Jun 5, 2:52 pm, [EMAIL PROTECTED] wrote:
>
> > > I am embedding Python in a MSVC++ (2005) application. The application
> > > creates some environment and then launches a Python script that will
> > > call some functions exported from the MSVC++ application.
>
> > > I want to be able to debug the Python script by using a debug server,
> > > likeWinpdb(winpdb.org).
>
> > > I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb
> > > 1.3.8.
>
> > > When I launch a script like "e:>python test.py" everything is O'K and
> > > I can useWinpdbto trace/debug.
>
> > > When I run the same script from the MSVC++ application, there is
> > > always a complain "ImportError: No module named _socket".
>
> > > Here is the basic test script I use:
>
> > > def Process( something ):
> > > print "\n\nStarted debugging\n=\n"
> > > #pydevd.settrace()
> > > import rpdb2; rpdb2.start_embedded_debugger("1")
> > > print "\n\nStopped debugging\n=\n"
>
> > > if __name__ == '__main__':
> > > Process( "test" )
> > > <<<
>
> > > In the MSVC++ application I tried many approaches, as suggested by
> > > many people, and all of them work to launch the script, but none of
> > > them works withWinpdb(or PyDev for Eclipse - same problem). Just for
> > > completeness - here is one:
>
> > >   PyRun_SimpleString("import sys");
> > >   PyRun_SimpleString("import os");
> > >   PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" );
> > >   PyRun_SimpleString( "g = globals().copy()" );
> > >   PyRun_SimpleString( "g['__file__'] = fullpath");
> > >   PyRun_SimpleString( "execfile(fullpath, g) ");
> > > <<<
>
> > > If I use pdb (import pdb + pdb.runcall(something) ) everything works
> > > fine, but I need the performance and convinience ofWinpdb.
>
> > > What am I doing wrong?
>
> > > Your help is highly appreciated!
>
> > > Best regards,
> > > Chris
>
> Nir,
>
> > Does this work?
>
> Unfortunately, not.
>
> I did some experiments to check the sys.path hypothesis:
>
> - In my MSVC++ application I did PyRun_SimpleString("import cgi"); -
> it complained about missing _socket.
>
> - Did PyRun_SimpleString("print sys.path") to get the sys.path as seen
> from within the application environment (that does not find _socket)
>
> - Did the same in "test.py" and ran ...>Python test.py to get the
> sys.path for the environment that _does_ find _socket
>
> - Compared the two - the working environment had two more paths:
>
>   C:\\WINDOWS\\system32\\python25.zip
>   C:\\Python25\\lib\\plat-win
>
> - Added the missing path to the embedded environment:
>
>   PyRun_SimpleString("import sys");
>   PyRun_SimpleString("import os");
>
>   PyRun_SimpleString("sys.path.append(\"C:\\WINDOWS\\system32\
> \python25.zip\")");
>   PyRun_SimpleString("sys.path.append(\"C:\\Python25\\lib\\plat-win
> \")");
>
>   PyRun_SimpleString("print sys.path");
>
>   PyRun_SimpleString("import cgi");
>
> Not all paths that are in the working environment are present in the
> embedded environment, but still there is a problem:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\Lib\cgi.py", line 40, in 
> import urllib
>   File "c:\Python25\lib\urllib.py", line 26, in 
> import socket
>   File "c:\Python25\lib\socket.py", line 45, in 
> import _socket
> ImportError: No module named _socket
>
> Chris

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


Re: Dynamically naming objects.

2008-06-06 Thread Paul
Something like this?

class User:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
n = 10
users = []

for i in range(n):
users.append(User('user%d' % i))

print users[9]
print users[4]

Cheers,

Paul


On Sat, Jun 7, 2008 at 3:59 AM, Kalibr <[EMAIL PROTECTED]> wrote:

> I've been developing a small script to fiddle with classes, and came
> accross the following problem. Assuming I get some user input asking
> for a number, how would I spawn 'n' objects from a class?
>
> i.e. I have a class class 'user' and I don't know how many of them I
> want to spawn.
>
> Any ideas?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Do this as a list comprehension?

2008-06-06 Thread Terry Reedy

"Mensanator" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On Jun 6, 1:44 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Mensanator" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | On Jun 5, 10:42?pm, John Salerno <[EMAIL PROTECTED]> wrote:
> | > Is it possible to write a list comprehension for this so as to 
> produce
> a
> | > list of two-item tuples?
> | >
> | > base_scores = range(8, 19)
> | > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]
> | > print zip(base_scores, score_costs)
> | >
> | > I can't think of how the structure of the list comprehension would 
> work
> | > in this case, because it seems to require iteration over two separate
> | > sequences to produce each item in the tuple.
>
> Which is exactly the purpose of zip, or its specialization enumerate!

Aren't you overlooking the fact that zip() truncates the output
to the shorter length iterable?
=

 No.
=
And since the OP foolishly
hardcoded his range bounds, zip(base_scores,score_cost) will
silently return the wrong answer if the base_count list grows.

 So, to future proof his code he should better use 
zip(itertools.count(8), score_costs).  I consider this better than using 
enumerate to make the wrong pairing (with itertools.count(0)) and then 
correcting the mistake.

Surely enumerate() wasn't added to Python with no intention of
ever being used.

 Of course not, so why suggest that is was?
However, it was intended for the most common case when one wants to pair 
items with counts beginning with 0.
=
> Of course, enumerate(iterable) is just a facade over 
> zip(itertools.count(),
> iterable)

But if all I'm using itertools for is the count() function, why would
I go to the trouble of importing it when I can simply use enumerate()?

I have no idea.  The purpose of enumerate is to be easy.
But it is not so easy when it gives the wrong pairings.
===
Is it a couple orders of magnitude faster?
=
 Perhaps you do not understand 'facade' - the front part or face of 
something that you see.  I was saying that enumerate is a face on a room 
containing zip and itertools.count, or the equivalent code thereof. 
Therefore, enumerate is an easy way to do a particular zip, not an 
alternative to zip.  And there should be no significant performance 
difference, certainly for long sequences which make the additional lookups 
irrelevant.

tjr




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


Re: Dynamically naming objects.

2008-06-06 Thread Hans Nowak

Kalibr wrote:

I've been developing a small script to fiddle with classes, and came
accross the following problem. Assuming I get some user input asking
for a number, how would I spawn 'n' objects from a class?

i.e. I have a class class 'user' and I don't know how many of them I
want to spawn.

Any ideas?


Sure. This will give you a list of n instances of user:

  [user() for i in range(n)]

Of course, you could also use a good old for loop:

  for i in range(n):
  u = user()
  ...do something with u...

Hope this helps!

--
Hans Nowak (zephyrfalcon at gmail dot com)
http://4.flowsnake.org/
--
http://mail.python.org/mailman/listinfo/python-list


Dynamically naming objects.

2008-06-06 Thread Kalibr
I've been developing a small script to fiddle with classes, and came
accross the following problem. Assuming I get some user input asking
for a number, how would I spawn 'n' objects from a class?

i.e. I have a class class 'user' and I don't know how many of them I
want to spawn.

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


need really help

2008-06-06 Thread Golu
respected please help me i am really need of money please pay me
through donation from my site. http://www.computersolution.co.cc i
will be very thankful to you . please donate atleast 5$ or 2$ through
my site
http://www.computersolution.co.cc hope i will be able to clear my
debts because of you all
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do this as a list comprehension?

2008-06-06 Thread Mensanator
On Jun 6, 1:40 pm, The Pythonista <[EMAIL PROTECTED]> wrote:
> On Thu, 05 Jun 2008 23:42:07 -0400, John Salerno wrote:
> > Is it possible to write a list comprehension for this so as to produce a
> > list of two-item tuples?
>
> > base_scores = range(8, 19)
> > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] print zip(base_scores,
> > score_costs)
>
> score_costs = [(base_scores[i], score_costs[i]) for i in range (len
> (base_scores))]

What happens if your iterables aren't the same length?

>
> But, I'd rather just use zip. :-)

And with zip() you won't get an error, but it won't be correct,
either.

>
> --
> code.py: A blog about life, the universe, and Python
>
> http://pythonista.wordpress.com
> ** Posted fromhttp://www.teranews.com**

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


Re: Do this as a list comprehension?

2008-06-06 Thread Mensanator
On Jun 6, 3:19 pm, "John Salerno" <[EMAIL PROTECTED]> wrote:
> "Mensanator" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> On Jun 6, 1:44 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>
> > "Mensanator" <[EMAIL PROTECTED]> wrote in message
>
> And since the OP foolishly
> hardcoded his range bounds
>
> Hmm, I just love the arrogance of some people. I actually posted a response
> to my own thread that asked about this situation of how best to make the
> range, but it doesn't seem to have posted.

It wasn't meant to be arrogant. Just that you must be careful
with zip() because it will not throw an exception if the two
iterables are of different length (this behaviour is by design)
but simply return tuples for the shorter of the iterables.

Hardcoding the range bounds instead of setting them dynamically
is a classic cause of this type of error. Obviously, you want the
range to start with 8, but what should be the upper bound?
The start plus the length of the other iterable keeping in mind
that if length is 11, last index is 8+10 since counting starts at 0.

So you want

range(8,8+len(score_costs))

Using enumerate() means you don't have to figure this out and
you'll never get an error or bad results that don't make an
error.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to send a POST request?

2008-06-06 Thread Jeff McNeil
The original urllib module will do it too, if you pass a data keyword
argument to urllib.urlopen:

u = urllib.urlopen('http://www.domain.com/cgi-bin/cgi.py',
data=urllib.urlencode({'name': 'pythonguy'}))


On Fri, Jun 6, 2008 at 6:04 PM, kj <[EMAIL PROTECTED]> wrote:
> In <[EMAIL PROTECTED]> kj <[EMAIL PROTECTED]> writes:
>
>>Hi.  Sorry for this very clueless question, but how does one write
>>in Python an HTTP client that can send a POST request?  The modules
>>I've found (e.g. urllib, urllib2), as far as I can tell, seem to
>>be limited to GET requests.  (I could be wrong though; please
>>correct me if this is so.)
>
> Sorry, my mistake.  I now see that urllib2 handles POSTs too.
>
> kynn
>
> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-06-06 Thread Jan Claeys
Op Fri, 23 May 2008 14:00:33 -0700, schreef [EMAIL PROTECTED]:

> Now this I can tell is false. The problem is not that it's difficult to
> "make a native compiler for" dynamic languages, the problem is that it's
> difficult to write native compiler for dynamic languages that generates
> code that beats the VM/byte-code interpreter/whatever you name it to be
> wotrh the effort.

Well, it would be much easier if there would be hardware that was 
designed for object oriented & dynamic programming...  ;-)

(Most current hardware is designed for use with C & similar languages, or 
sometimes for massively parrallel computing (e.g. GPUs), but the last 
tries to design hardware to fit something like Python date back to the 
1980s AFAIK...)


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


Re: File-writing not working in Windows?

2008-06-06 Thread John Machin
On Jun 7, 1:18 am, [EMAIL PROTECTED] wrote:
> All,
>

[code snipped]

>
> This code works PERFECTLY in Linux.  Where I have a match in the file
> I'm processing, it gets cut out from the start of the match until the
> end of the match, and written to the temporary file in tempdir.
>
> It does not work in Windows.  It does not create or write to the
> temporary file AT ALL.  It creates the tempdir directory with no
> problem.
>
> Here's the kicker: it works perfectly in Windows if Windows is running
> in VMware on a Linux host!  (I assume that that's because VMware is
> passing some call to the host.)
>
> Can anyone tell me what it is that I'm missing which would prevent the
> file from being created on Windows natively?
>
> I'm sorry I can't provide any more of the code, and I know that that
> will hamper your efforts in helping me, so I apologise up front.
>
> Assumptions:
> You can assume self.checkbox25.GetValue() is always false for now, and
> self.Info[x][0] contains a two character string like "00" or "09" or
> "14".  There is always a match in the fileTarget, so self.Info[x][2]
> will always be true at some point, as will self.Info[x][4].  I am
> cutting an HTML file at predetermined comment sections, and I have
> control over the HTML files that are being cut.  (So I can force the
> file to match what I need it to match if necessary.)

Assume nothing. Don't believe anyone who says "always". Insert some
print statements and repr() calls to show what's actually there.

> I hope however that it's something obvious that a Python guru here
> will be able to spot and that this n00b is missing!

*IF* the problem is in the code, it would be easier to spot if you had
removed large chunks of indentation before posting.

Less is more: change "if (foo == 2):" to "if foo == 2:", "foo == True"
to "foo", and "foo == False" to "not foo".

Browse http://www.python.org/dev/peps/pep-0008/

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


Re: readline() & seek() ???

2008-06-06 Thread Kam-Hung Soh

Chris wrote:

On Jun 6, 5:13 am, Kam-Hung Soh <[EMAIL PROTECTED]> wrote:

Tim Roberts wrote:

DataSmash <[EMAIL PROTECTED]> wrote:

I have a text file that contains thousands of lines and each line is
256 characters long.
This is my task:
For each line in the file, move to the 25th character, if the
character is a "T",
move to the 35th character of the line and read 5 characters from
there.
Capture these 5 characters and write them to a new text file, each 5
characters separated by a comma.
I appreciate your help!

Did you even TRY this?  Your task reads like pseudocode that translates
virtually line-for-line to Python code.
  fout = open('outputfile.txt','w')
  for line in open('inputfile.txt'):
  if line[24] == 'T':
  fout.write( line[34:39] + ',' )

Should the last line be ...

fout.write(','.join(line[34:39])

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman


each 5 characters need to be delimited by a comma, your statement
would have a comma between each of the 5 characters.


You're right; I see where I got confused.

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: how to build a street with more than 1 house ?

2008-06-06 Thread Tommy Grav


On Jun 6, 2008, at 6:45 PM, Stef Mientki wrote:


hello,

In the code below, I can build a large street like this:
large_street = house * 25
but not a small street. like this:
small_street = 5 * house


This calls the int.__mul__() code i believe.


Why is this different ?
And more interesting, how do I get the right results ?


If memory serves me right look into __rmul__().

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


Re: Newbie question, list comprehension

2008-06-06 Thread Johannes Bauer

Hans Nowak schrieb:


In this case, you can just use a slice, as localtime is a tuple:

fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % localtime[:6]

Hope this helps! ^_^


Ahh, how cool! That's *exactly* what I meant with "awesome Python magic" :-)

Amazing language, I have to admit.

Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
  in de.sci.electronics <[EMAIL PROTECTED]>
--
http://mail.python.org/mailman/listinfo/python-list


how to build a street with more than 1 house ?

2008-06-06 Thread Stef Mientki

hello,

In the code below, I can build a large street like this:
 large_street = house * 25
but not a small street. like this:
 small_street = 5 * house

Why is this different ?
And more interesting, how do I get the right results ?

thanks,
Stef Mientki

class type_house ( object ) :
 def __init__( self, front_doors = 1 ) :
   self.front_doors = front_doors
 def __mul__ ( self, b ) :
   return type_house ( self.front_doors * b )

house = type_house ()
large_street = house * 25
print large_street.front_doors
small_street = 5 * house
print small_street.front_doors

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


Re: Change in interactive interpreter?

2008-06-06 Thread The Pythonista
On Fri, 06 Jun 2008 11:36:13 -0700, Gary Herron wrote:
   
> Try again.  I think you'll find it's still there -- although you have to
> execute a something that returns a value before it's set for the first
> time.

That was, indeed the problem.  Boy do I feel silly now. :-)

Thanks

-- 
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question, list comprehension

2008-06-06 Thread Hans Nowak

Johannes Bauer wrote:

Hello group,

I'm currently doing something like this:

import time
localtime = time.localtime(1234567890)
fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1], 
localtime[2], localtime[3], localtime[4], localtime[5])

print fmttime

For the third line there is, I suppose, some awesome python magic I 
could use with list comprehensions. I tried:


fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in 
range(0, 5)])


The % operator here wants a tuple with six arguments that are integers, not a 
list.  Try:


fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % tuple(localtime[i] for i in 
range(6))


As it appearently passed the while list [2009, 02, 14, 0, 31, 30] as the 
first parameter which is supposed to be substituted by "%04d". Is there 
some other way of doing it?


In this case, you can just use a slice, as localtime is a tuple:

fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % localtime[:6]

Hope this helps! ^_^

--
Hans Nowak (zephyrfalcon at gmail dot com)
http://4.flowsnake.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to send a POST request?

2008-06-06 Thread kj
In <[EMAIL PROTECTED]> kj <[EMAIL PROTECTED]> writes:

>Hi.  Sorry for this very clueless question, but how does one write
>in Python an HTTP client that can send a POST request?  The modules
>I've found (e.g. urllib, urllib2), as far as I can tell, seem to
>be limited to GET requests.  (I could be wrong though; please
>correct me if this is so.)

Sorry, my mistake.  I now see that urllib2 handles POSTs too.

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
--
http://mail.python.org/mailman/listinfo/python-list


Newbie question, list comprehension

2008-06-06 Thread Johannes Bauer

Hello group,

I'm currently doing something like this:

import time
localtime = time.localtime(1234567890)
fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1], 
localtime[2], localtime[3], localtime[4], localtime[5])

print fmttime

For the third line there is, I suppose, some awesome python magic I 
could use with list comprehensions. I tried:


fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in 
range(0, 5)])


But that didn't work:

Traceback (most recent call last):
  File "./test.py", line 8, in ?
fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in 
range(0, 5)])

TypeError: int argument required

As it appearently passed the while list [2009, 02, 14, 0, 31, 30] as the 
first parameter which is supposed to be substituted by "%04d". Is there 
some other way of doing it?


Thanks a lot,
Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
  in de.sci.electronics <[EMAIL PROTECTED]>
--
http://mail.python.org/mailman/listinfo/python-list


How to send a POST request?

2008-06-06 Thread kj



Hi.  Sorry for this very clueless question, but how does one write
in Python an HTTP client that can send a POST request?  The modules
I've found (e.g. urllib, urllib2), as far as I can tell, seem to
be limited to GET requests.  (I could be wrong though; please
correct me if this is so.)

TIA!

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning which modules were loaded

2008-06-06 Thread Gary Herron

James Stroud wrote:
I am rolling up a distribution of a program I wrote. It uses 
matplotlib with tkagg so the bundle is HUGE (47 MB, 14 MB after bz 
compression). Is there any way to run the program, put it through all 
of its paces, and then inspect which modules were loaded. I would like 
to gather these in a list and delete any others that py2app and py2exe 
attempt to include. Currently, these (or py2app, at least) use 
dependency graphing and icnlude everything belonging to pylab, 
matplotlib, and numpy by default. I don't want everything, I only want 
what my program needs to run. For example, some modules are imported 
by functions (in Pmw, for example) that never get called. I don't want 
to include these.


Thanks in advance for any help.

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


Import sys, then look at sys.modules.  It's a dictionary that contains 
all the imported modules, but I suspect you'll find that it's much 
easier to let py2app and py2exe determine what's imported than it is to 
go through sys.modules yourself.


Gary Herron

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


Learning which modules were loaded

2008-06-06 Thread James Stroud
I am rolling up a distribution of a program I wrote. It uses matplotlib 
with tkagg so the bundle is HUGE (47 MB, 14 MB after bz compression). Is 
there any way to run the program, put it through all of its paces, and 
then inspect which modules were loaded. I would like to gather these in 
a list and delete any others that py2app and py2exe attempt to include. 
Currently, these (or py2app, at least) use dependency graphing and 
icnlude everything belonging to pylab, matplotlib, and numpy by default. 
I don't want everything, I only want what my program needs to run. For 
example, some modules are imported by functions (in Pmw, for example) 
that never get called. I don't want to include these.


Thanks in advance for any help.

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


Re: Q about object identity

2008-06-06 Thread Tommy Grav


On Jun 6, 2008, at 4:27 PM, Ethan Furman wrote:


[EMAIL PROTECTED] wrote:

Hello,
I am testing object identity.
If I do it from the interpreter, I get strange results.

*print [] is []*

*False*

print id([]), id([])

3083942700 3083942700
Why is that? Isn't this an error?


in the first statement the two []'s are in memory at the same
time and have different id() signatures. For the second statement
the first id([]) is evaluated and release from memory and then
the second id([]) is evaluated and release from memory. Since
only one of them exist at a time they can have the same id()
signature.

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


Macro like functionality for shorthand variable names

2008-06-06 Thread Tilman Kispersky
I have python code in a class method translated from C++ that looks
sort of like this:

>>>  self.dydt[1] = self.a * (self.b * self.y[0] - self.y[1])


To make this more readable in C++ I had made macros to achieve this:
#define du (dydt[1])
#define u (y[1])
#define V (y[0])

du = a * (b * V - u);


I realize the value of not having macros in Python.  They've tripped
me up more than once in C++.  My question is:
Is there any way to write a shorterhand more readable version of the
python code above?  I'm doing several calculations one after the other
and some of the lines are quite long.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Q about object identity

2008-06-06 Thread Ethan Furman

[EMAIL PROTECTED] wrote:

Hello,

I am testing object identity.

If I do it from the interpreter, I get strange results.



*print [] is []*


*False*



print id([]), id([])


3083942700 3083942700



Why is that? Isn't this an error?


If I test it in a script, all is OK.

#!/usr/bin/python

a = []
b = []

print a == b
*print a is b*

print id(a), id(b)

print id(None), id(None)
print id(True), id(True)


On my computer, I got these results:

True
*False*
3083769036 3083793516
135553336 135553336
135526444 135526444

All as expected.


jan bodnar


Assuming I'm not missing something obvious here, the results from the 
script are the same as those from the interpreter -- the _is_ returns 
False in both cases.

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


Re: Guide to organizing modules?

2008-06-06 Thread Casey McGinty
>
> Yes, in the above post I meant to say package where I said module.
> Right now all my functions are in the __init__.py script, and I would
> consider separating them out into sub-packages, if it had any rhyme or
> reason, but right now that escapes me. That's mostly what I'm trying
> to ask for.
>
> Thanks,
> --Buck
>  
>

Have you thought about  creating a number of new module files in your
package, and importing them into __init__.py? If you do that you could hide
the fact that the functions are in distinct files from outside of the
package.

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

[ANN] Dramatis 0.1.1 released

2008-06-06 Thread Steven Parkes
The first alpha release of dramatis hit the streets today.

dramatis is a library available in Python and Ruby used to write concurrent
programs based on the actor model of concurrency.

The dramatis web site is http://dramatis.mischance.net

The release is available as a python distutils package at
http://pypi.python.org/pypi/dramatis. It supports both Ruby and Python, and
comes with API docs, several examples, and a tutorial.

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


Re: ClassName.attribute vs self.__class__.attribute

2008-06-06 Thread Casey McGinty
On Thu, Jun 5, 2008 at 11:39 AM, Terry Reedy <[EMAIL PROTECTED]> wrote:

>
> If you want to access the attribute of a particular class, to read or
> write, use that class.
>   SomeClass.attr
> Note that no instance is required or relevant.
>
> If you want to read the attrubute of the class of an instance (or the first
> superclass with the attribute, whatever that class might be, use self.attr
> or self.__class__.attr.  (Use the latter if the instance has (or might
> have) an attribute of the same name).
>
> For setting an attribute, self.attr = x sets it on the instance while
> self.__class__.attr = x sets it on its class.
>  
>

So the key here is that obj.__class__.attr  will only access  the immediate
child class name space, but SuperClass.attr will guarantee your are access
the first super class namespace? If that is true, then the bug makes sense.
--
http://mail.python.org/mailman/listinfo/python-list

Re: File-writing not working in Windows?

2008-06-06 Thread jay graves
On Jun 6, 3:19 pm, [EMAIL PROTECTED] wrote:
> This did not make a difference in my script.  However, I did what you
> suggested, and tried the simple script it Windows, and it works as it
> should.
> (It's really annoying because it works on the Mac and Linux!  (I just
> tested my script on the Mac as well.)  It only doesn't work on
> Windows, though clearly the file processing I am doing SHOULD work.)

Is there a global exception handler somewhere in your code that could
be eating an error that only happens on windows?  (something weird
like file permissions.)  I'm really at a loss.

Sorry.

...
Jay




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


Re: Do this as a list comprehension?

2008-06-06 Thread John Salerno
"Mensanator" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On Jun 6, 1:44 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Mensanator" <[EMAIL PROTECTED]> wrote in message

And since the OP foolishly
hardcoded his range bounds

Hmm, I just love the arrogance of some people. I actually posted a response 
to my own thread that asked about this situation of how best to make the 
range, but it doesn't seem to have posted. 


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


Re: File-writing not working in Windows?

2008-06-06 Thread tdahsu
On Jun 6, 2:58 pm, jay graves <[EMAIL PROTECTED]> wrote:
> On Jun 6, 1:22 pm, [EMAIL PROTECTED] wrote:
>
> > I am thinking that the "g.open(tempFileName, 'a')" command is the
> > issue.  Is there anything different about opening a file in Windows?
> > Does Windows understand "append", or would I have to do control checks
> > for seeing if the file is created and then appending?
>
> Does your file have embedded nulls?
> Try opening it in binary mode.
>
> g.open(tempFileName,'ab')
>
> Note that this will turn off Universal newline support.
>
> Barring that, can you distill the problem down by writing a script
> that exhibits the behavior without the rest of your program?
>
> ...
> Jay

Jay,

This did not make a difference in my script.  However, I did what you
suggested, and tried the simple script it Windows, and it works as it
should.

(It's really annoying because it works on the Mac and Linux!  (I just
tested my script on the Mac as well.)  It only doesn't work on
Windows, though clearly the file processing I am doing SHOULD work.)

Now I have to find out what it is about my code that's causing the
problem...  :-(
--
http://mail.python.org/mailman/listinfo/python-list


Trying to install mysql lib for python

2008-06-06 Thread [EMAIL PROTECTED]
Hi
How do I install mysql db libray for python?
I went to source forg and downloaded the following zip folder

MySQL_python-1.2.2-py2.4-win32
I open the folder and looked inside did not see any directions.

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


Re: noob question : library versus normal python files

2008-06-06 Thread [EMAIL PROTECTED]
On 6 juin, 19:36, रवींदर ठाकुर (ravinder thakur)
<[EMAIL PROTECTED]> wrote:
> hello friends,
>
> i have a python library(rdflib) that i am using in some project using
> Google App Engine. I have developed everything using this on my local
> machine and things work fine. But in my final deployment, i have to
> use it in source code form rather than in library form.

What do you mean "library form" ?
--
http://mail.python.org/mailman/listinfo/python-list

Re: Assigning to __class__ : bad form?

2008-06-06 Thread [EMAIL PROTECTED]
On 6 juin, 19:51, The Pythonista <[EMAIL PROTECTED]> wrote:
> I've been wondering for a while about whether assigning to __class__ is
> bad form or not.  Specifically, I mean doing so when some other method of
> implementing the functionality you're after is available (i.e. using an
> adapter, or something like the strategy pattern).
>
> To give an example and a non-example of what I'm talking about, consider
> the following recipes from the online Python Cookbook:
>
> Ring Buffer:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429
>
> In this case, I think the assignment to __class__ just obfuscates things,
> and the example would be better coded as a single class.
>
> On the other hand,
>
> Fast copy of an object having a slow __init__ : http://
> aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66507
>
> This seems like a reasonable use case for assigning to __class__ (except
> that it's already implemented in the 'new' module, but, read the Martelli-
> bot's comments near the end of the recipe).  I consider this a reasonable
> use case for assigning to __class__, because, short of the 'new' module,
> I don't see any other way to accomplish it.
>
> So, what is the opinion of the broader Python community?

My first opinion is that your formulation, ie "assigning *to*
__class__" is perhaps a bit misleading. What you're talking about is
rebinding the __class__ attribute, while, from your subject line, I
thought you were talking about reassigning to (rebinding) a class
attribute from the instance, ie : self.__class__.attrib = value.

Now to the point:

>  Is code that
> assigns to __class__ just clever trickiness to be avoided, or is it
> sometimes a good thing?

Both, definitively !-)

Like most of Python's "advanced" features, it's nice to have it
because it can easily solve problems that would otherwise be at best a
PITA, but it's not something you use on a daily basis - nor without
thinking twice. And obviously, there's no clear rule here, except good
taste and common sense. Anyway, the mere fact that you're asking
yourself if it's a good idea in such or such case is a probably a good
indication that you'll find out by yourself the day you'll be tempted
to use this trick whether it's a good or bad idea in this particular
context.
--
http://mail.python.org/mailman/listinfo/python-list


Re: File-writing not working in Windows?

2008-06-06 Thread jay graves
On Jun 6, 1:22 pm, [EMAIL PROTECTED] wrote:
> I am thinking that the "g.open(tempFileName, 'a')" command is the
> issue.  Is there anything different about opening a file in Windows?
> Does Windows understand "append", or would I have to do control checks
> for seeing if the file is created and then appending?

Does your file have embedded nulls?
Try opening it in binary mode.

g.open(tempFileName,'ab')

Note that this will turn off Universal newline support.

Barring that, can you distill the problem down by writing a script
that exhibits the behavior without the rest of your program?

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


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread Russ P.
On Jun 6, 8:28 am, Bruno Desthuilliers  wrote:
> Russ P. a écrit :
>
>
>
> > On Jun 5, 2:27 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> >> On Thu, 5 Jun 2008 11:36:28 -0700 (PDT), "Russ P."
> >> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
> >>> would need to use a "mangled" name to access private data or methods.
> >>> But you will be using the name many times, you can reassign your own
> >>> name, of course, so the mangled name need not appear more than once
> >>> where it is needed.
> >> Which will break the first time the "innards" rebind a value to the
> >> mangled name, as the "simplified" external name will still be bound to
> >> the previous value.
>
> > I'm not sure you understood what I meant. In current Python, if I need
> > access to data element __XX in class YourClass, I can use
> > ZZ._YourClass__XX, but if I don't want to clutter my code with that
> > mangled name, I can just write
>
> > XX = ZZ._YourClass__XX
>
> > and refer to it from that point on as XX.
>
> > Obviously if the meaning of
> > __XX changes within class ZZ, this will break, but that's why you are
> > supposed to avoid using private data in the first place.
>
> AFAICT, What Dennis meant is that the binding of ZZ._YourClass__XX
> changes between the moment you bind it to local XX and the moment you
> use it, then you're out.

Perhaps I should have stipulated that this should be done only in a
local scope and in an application that is not multi-threaded. Then I
don't see how you can have a problem.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread Russ P.
On Jun 6, 8:25 am, Bruno Desthuilliers  wrote:

> >>> I also realize, by the way, that Python allows a client of a class to
> >>> define a new class member from completely outside the class
> >>> definition. Obviously, that cannot be declared private.
> >> Why so ?
>
> > Why should the client of a class not be able to declare a *private*
> > member of the class? You're kidding, right?
>
> I'm dead serious. I often add implementation attributes to either a
> class or an instance. These *are* implementation parts, not API.

If a client accesses a data member of a class, then by definition that
member is not really private, so letting the client create a new data
member and declare it as private seems a bit silly to me. Actually,
just letting the client create the new data member, private or not,
seems like a bit of a stretch to me, but I'll leave that be.

> > For the record, I have made it abundantly clear that I don't think
> > Python should not have as rigorous an encapsulation regime as C++ or
> > Java. The worst that could happen with my proposition is that you
> > would need to use a "mangled" name to access private data or methods.
>
> That's already the case - when you use __name_mangling. And if there's
> no effective access restriction, then what the point of having this
> 'priv' keyword ?
>
> > But you will be using the name many times, you can reassign your own
> > name, of course, so the mangled name need not appear more than once
> > where it is needed.
>
> Once again, I just don't see the point. Either you want effective access
> restriction in Python, or you don't. And if you don't, what would this
> 'priv' keyword be useful to ?

In the end, I suppose it boils down to aesthetics and personal
preference.

The leading-underscore convention bothers me for two reasons: (1) like
the OP, I don't like the way it makes my code look, and (2) it is a
signal to a person reading the code, but it has no actual effect in
the interpreter.

I think the concept of private data and methods is important enough to
be implemented with more than just a tacky naming convention. That is
why I suggested the "priv" keyword. At the same time, I realize that
people will occasionally be frustrated if they are rigorously denied
access to all private data, which is why I suggested an "indirect"
method of access through mangled names.

You can argue that such indirect access defeats the whole idea of
private data, but at least it alerts the client to the fact that he
(or she or it) is accessing private data -- and it does so without
using Hungarian notation.

I would let the "priv" keyword also be used for data or functions at
file scope. It just seems logical to me. Again, some name mangling
convention could be concocted for those who think they really need
access.

Actually, the whole objection to denied access baffles me a bit. Does
anyone object to not having access from outside a function to local
variables within the function? I doubt it. The other thing is that the
vast majority of Python software, I would guess, is provided with
source code. How many Python applications or libraries are provided
without source code? If you have the source code, you can obviously
just delete the "priv" keyword anywhere or everywhere it appears. And
if you have a major client who insists on access to all the internals,
just delete all occurrences of "priv" before you ship the code (or
don't use it to start with).

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


Re: How to kill a thread?

2008-06-06 Thread The Pythonista
It's always been my understanding that you can't forcibly kill a thread 
in Python (at least not in a portable way).  The best you can do is 
politely ask it to die, IIRC.

-- 
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do this as a list comprehension?

2008-06-06 Thread The Pythonista
On Thu, 05 Jun 2008 23:42:07 -0400, John Salerno wrote:

> Is it possible to write a list comprehension for this so as to produce a
> list of two-item tuples?
> 
> base_scores = range(8, 19)
> score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] print zip(base_scores,
> score_costs)
> 

score_costs = [(base_scores[i], score_costs[i]) for i in range (len 
(base_scores))]

But, I'd rather just use zip. :-)

-- 
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: Change in interactive interpreter?

2008-06-06 Thread Gary Herron

The Pythonista wrote:
I remember the interactive interpreter used to define the name _ to 
return the value of the last expression that was evaluated.  However, I 
tried it just today and got a NameError.  Is this a change in the 
interpreter or is there a configuration option I need to set to enable it?


Thanks!

  


Try again.  I think you'll find it's still there -- although you have to 
execute a something that returns a value before it's set for the first time.


Gary Herron


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


Re: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket

2008-06-06 Thread Chris8Boyd
On Jun 6, 11:25 am, [EMAIL PROTECTED] wrote:
> On Jun 6, 1:13 am, Nir <[EMAIL PROTECTED]> wrote:
>
>
>
> > You seem to be having a problem with the import path of the embedded
> > interpreter. I suppose the embedded interpreter includes some modules
> > in a particular folder and _socket is not one of them. For the sake of
> > debugging try adding the c:\python25\lib path to the sys.path variable
> > of the interpreter before attempting to import rpdb2.
>
> > Does this work?
>
> > Nir
>
> > On Jun 5, 2:52 pm, [EMAIL PROTECTED] wrote:
>
> > > I am embedding Python in a MSVC++ (2005) application. The application
> > > creates some environment and then launches a Python script that will
> > > call some functions exported from the MSVC++ application.
>
> > > I want to be able to debug the Python script by using a debug server,
> > > likeWinpdb(winpdb.org).
>
> > > I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb
> > > 1.3.8.
>
> > > When I launch a script like "e:>python test.py" everything is O'K and
> > > I can useWinpdbto trace/debug.
>
> > > When I run the same script from the MSVC++ application, there is
> > > always a complain "ImportError: No module named _socket".
>
> > > Here is the basic test script I use:
>
> > > def Process( something ):
> > > print "\n\nStarted debugging\n=\n"
> > > #pydevd.settrace()
> > > import rpdb2; rpdb2.start_embedded_debugger("1")
> > > print "\n\nStopped debugging\n=\n"
>
> > > if __name__ == '__main__':
> > > Process( "test" )
> > > <<<
>
> > > In the MSVC++ application I tried many approaches, as suggested by
> > > many people, and all of them work to launch the script, but none of
> > > them works withWinpdb(or PyDev for Eclipse - same problem). Just for
> > > completeness - here is one:
>
> > >   PyRun_SimpleString("import sys");
> > >   PyRun_SimpleString("import os");
> > >   PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" );
> > >   PyRun_SimpleString( "g = globals().copy()" );
> > >   PyRun_SimpleString( "g['__file__'] = fullpath");
> > >   PyRun_SimpleString( "execfile(fullpath, g) ");
> > > <<<
>
> > > If I use pdb (import pdb + pdb.runcall(something) ) everything works
> > > fine, but I need the performance and convinience ofWinpdb.
>
> > > What am I doing wrong?
>
> > > Your help is highly appreciated!
>
> > > Best regards,
> > > Chris
>
> Nir,
>
> > Does this work?
>
> Unfortunately, not.
>
> I did some experiments to check the sys.path hypothesis:
>
> - In my MSVC++ application I did PyRun_SimpleString("import cgi"); -
> it complained about missing _socket.
>
> - Did PyRun_SimpleString("print sys.path") to get the sys.path as seen
> from within the application environment (that does not find _socket)
>
> - Did the same in "test.py" and ran ...>Python test.py to get the
> sys.path for the environment that _does_ find _socket
>
> - Compared the two - the working environment had two more paths:
>
>   C:\\WINDOWS\\system32\\python25.zip
>   C:\\Python25\\lib\\plat-win
>
> - Added the missing path to the embedded environment:
>
>   PyRun_SimpleString("import sys");
>   PyRun_SimpleString("import os");
>
>   PyRun_SimpleString("sys.path.append(\"C:\\WINDOWS\\system32\
> \python25.zip\")");
>   PyRun_SimpleString("sys.path.append(\"C:\\Python25\\lib\\plat-win
> \")");
>
>   PyRun_SimpleString("print sys.path");
>
>   PyRun_SimpleString("import cgi");
>
> Not all paths that are in the working environment are present in the
> embedded environment, but still there is a problem:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\Lib\cgi.py", line 40, in 
> import urllib
>   File "c:\Python25\lib\urllib.py", line 26, in 
> import socket
>   File "c:\Python25\lib\socket.py", line 45, in 
> import _socket
> ImportError: No module named _socket
>
> Chris

There is a typo:

"Not all paths that are in the working environment are present in the
embedded environment, but still there is a problem:"

should read

"Now all paths"

Sorry!

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


Change in interactive interpreter?

2008-06-06 Thread The Pythonista
I remember the interactive interpreter used to define the name _ to 
return the value of the last expression that was evaluated.  However, I 
tried it just today and got a NameError.  Is this a change in the 
interpreter or is there a configuration option I need to set to enable it?

Thanks!

-- 
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket

2008-06-06 Thread Chris8Boyd
On Jun 6, 1:13 am, Nir <[EMAIL PROTECTED]> wrote:
> You seem to be having a problem with the import path of the embedded
> interpreter. I suppose the embedded interpreter includes some modules
> in a particular folder and _socket is not one of them. For the sake of
> debugging try adding the c:\python25\lib path to the sys.path variable
> of the interpreter before attempting to import rpdb2.
>
> Does this work?
>
> Nir
>
> On Jun 5, 2:52 pm, [EMAIL PROTECTED] wrote:
>
> > I am embedding Python in a MSVC++ (2005) application. The application
> > creates some environment and then launches a Python script that will
> > call some functions exported from the MSVC++ application.
>
> > I want to be able to debug the Python script by using a debug server,
> > likeWinpdb(winpdb.org).
>
> > I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb
> > 1.3.8.
>
> > When I launch a script like "e:>python test.py" everything is O'K and
> > I can useWinpdbto trace/debug.
>
> > When I run the same script from the MSVC++ application, there is
> > always a complain "ImportError: No module named _socket".
>
> > Here is the basic test script I use:
>
> > def Process( something ):
> > print "\n\nStarted debugging\n=\n"
> > #pydevd.settrace()
> > import rpdb2; rpdb2.start_embedded_debugger("1")
> > print "\n\nStopped debugging\n=\n"
>
> > if __name__ == '__main__':
> > Process( "test" )
> > <<<
>
> > In the MSVC++ application I tried many approaches, as suggested by
> > many people, and all of them work to launch the script, but none of
> > them works withWinpdb(or PyDev for Eclipse - same problem). Just for
> > completeness - here is one:
>
> >   PyRun_SimpleString("import sys");
> >   PyRun_SimpleString("import os");
> >   PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" );
> >   PyRun_SimpleString( "g = globals().copy()" );
> >   PyRun_SimpleString( "g['__file__'] = fullpath");
> >   PyRun_SimpleString( "execfile(fullpath, g) ");
> > <<<
>
> > If I use pdb (import pdb + pdb.runcall(something) ) everything works
> > fine, but I need the performance and convinience ofWinpdb.
>
> > What am I doing wrong?
>
> > Your help is highly appreciated!
>
> > Best regards,
> > Chris

Nir,

> Does this work?

Unfortunately, not.

I did some experiments to check the sys.path hypothesis:

- In my MSVC++ application I did PyRun_SimpleString("import cgi"); -
it complained about missing _socket.

- Did PyRun_SimpleString("print sys.path") to get the sys.path as seen
from within the application environment (that does not find _socket)

- Did the same in "test.py" and ran ...>Python test.py to get the
sys.path for the environment that _does_ find _socket

- Compared the two - the working environment had two more paths:

  C:\\WINDOWS\\system32\\python25.zip
  C:\\Python25\\lib\\plat-win

- Added the missing path to the embedded environment:

  PyRun_SimpleString("import sys");
  PyRun_SimpleString("import os");

  PyRun_SimpleString("sys.path.append(\"C:\\WINDOWS\\system32\
\python25.zip\")");
  PyRun_SimpleString("sys.path.append(\"C:\\Python25\\lib\\plat-win
\")");

  PyRun_SimpleString("print sys.path");

  PyRun_SimpleString("import cgi");

Not all paths that are in the working environment are present in the
embedded environment, but still there is a problem:

Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\Lib\cgi.py", line 40, in 
import urllib
  File "c:\Python25\lib\urllib.py", line 26, in 
import socket
  File "c:\Python25\lib\socket.py", line 45, in 
import _socket
ImportError: No module named _socket

Chris



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


Re: File-writing not working in Windows?

2008-06-06 Thread tdahsu
On Jun 6, 11:35 am, jay graves <[EMAIL PROTECTED]> wrote:
> On Jun 6, 10:18 am, [EMAIL PROTECTED] wrote:
> 
>
> > This code works PERFECTLY in Linux.  Where I have a match in the file
> > I'm processing, it gets cut out from the start of the match until the
> > end of the match, and written to the temporary file in tempdir.
> > It does not work in Windows.  It does not create or write to the
> > temporary file AT ALL.  It creates the tempdir directory with no
> > problem.
>
> In general, I don't use string concatenation when building paths.
> Especially on scripts that are meant to run on multiple platforms.
>
> > Here's the kicker: it works perfectly in Windows if Windows is running
> > in VMware on a Linux host!  (I assume that that's because VMware is
> > passing some call to the host.)
>
> probably a red herring.
>
> > Can anyone tell me what it is that I'm missing which would prevent the
> > file from being created on Windows natively?
>
> Get rid of the 'posix' check and use os.path.join to create
> 'tempfileName' and see if it works.
>
> HTH.
> ...
> Jay Graves

Jay,

Thank you for your answer.  I have researched os.path.join.  I have
changed the code to read as follows:

if (self.checkbox25.GetValue() == False):
initialFileName = self.Info[x][0] + "_tmp_" + fileName + ".txt"
tempfileName = os.path.join("proctemp", initialFileName)
else:
initialFileName = self.Info[x][0] + "_xyz.txt"
tempfileName = os.path.join("proctemp", initialFileName)

this still works in Linux; it does not work in Windows.

I am thinking that the "g.open(tempFileName, 'a')" command is the
issue.  Is there anything different about opening a file in Windows?
Does Windows understand "append", or would I have to do control checks
for seeing if the file is created and then appending?
--
http://mail.python.org/mailman/listinfo/python-list


My company provide most popular of the shoes model, bag, clothes, Bikini swimwear, sunglasses and watch of etc..

2008-06-06 Thread hongfeng13
hello ! ! !welcome to visit our website  http://www.nikeadishoes.com
Our main products :  shoes Hoodies T-Shirt Jeans Jacket bags
Electronic and so on

we can supply many popular shoes model,bag,clothes ,bikini,sunglass
and watch and so on. We can give you products with good quality and
reasonable price! We are looking forward to do business with you. Do
not hesitate and contact with us!


[EMAIL PROTECTED]  products 100% authentic
MSN: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


My company provide most popular of the shoes model, bag, clothes, Bikini swimwear, sunglasses and watch of etc..

2008-06-06 Thread hongfeng13
hello ! ! !welcome to visit our website  http://www.nikeadishoes.com
Our main products :  shoes Hoodies T-Shirt Jeans Jacket bags
Electronic and so on

we can supply many popular shoes model,bag,clothes ,bikini,sunglass
and watch and so on. We can give you products with good quality and
reasonable price! We are looking forward to do business with you. Do
not hesitate and contact with us!


[EMAIL PROTECTED]  products 100% authentic
MSN: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Assigning to __class__ : bad form?

2008-06-06 Thread The Pythonista
I've been wondering for a while about whether assigning to __class__ is 
bad form or not.  Specifically, I mean doing so when some other method of 
implementing the functionality you're after is available (i.e. using an 
adapter, or something like the strategy pattern).

To give an example and a non-example of what I'm talking about, consider 
the following recipes from the online Python Cookbook:

Ring Buffer: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429

In this case, I think the assignment to __class__ just obfuscates things, 
and the example would be better coded as a single class.

On the other hand,

Fast copy of an object having a slow __init__ : http://
aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66507

This seems like a reasonable use case for assigning to __class__ (except 
that it's already implemented in the 'new' module, but, read the Martelli-
bot's comments near the end of the recipe).  I consider this a reasonable 
use case for assigning to __class__, because, short of the 'new' module, 
I don't see any other way to accomplish it.

So, what is the opinion of the broader Python community?  Is code that 
assigns to __class__ just clever trickiness to be avoided, or is it 
sometimes a good thing?

-- 
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do this as a list comprehension?

2008-06-06 Thread Mensanator
On Jun 6, 1:44 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Mensanator" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | On Jun 5, 10:42?pm, John Salerno <[EMAIL PROTECTED]> wrote:
> | > Is it possible to write a list comprehension for this so as to produce
> a
> | > list of two-item tuples?
> | >
> | > base_scores = range(8, 19)
> | > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]
> | > print zip(base_scores, score_costs)
> | >
> | > I can't think of how the structure of the list comprehension would work
> | > in this case, because it seems to require iteration over two separate
> | > sequences to produce each item in the tuple.
>
> Which is exactly the purpose of zip, or its specialization enumerate!

Aren't you overlooking the fact that zip() truncates the output
to the shorter length iterable? And since the OP foolishly
hardcoded his range bounds, zip(base_scores,score_cost) will
silently return the wrong answer if the base_count list grows.

Surely enumerate() wasn't added to Python with no intention of
ever being used.


>
> | > zip seems to work fine anyway, but my immediate instinct was to try a
> | > list comprehension (until I couldn't figure out how!). And I wasn't
> sure
> | > if list comps were capable of doing everything a zip could do.
> |
> | base_scores = range(8, 19)
> | score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]
> | print zip(base_scores, score_costs)
> |
> | s = [(i+8,j) for i,j in enumerate( [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])]
> | print s
> |
> | ##>>>
> | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15,
> | 2), (16, 2), (17, 3), (18, 3)]
> | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15,
> | 2), (16, 2), (17, 3), (18, 3)]
> | ##>>>
>
> Of course, enumerate(iterable) is just a facade over zip(itertools.count(),
> iterable)

But if all I'm using itertools for is the count() function, why would
I
go to the trouble of importing it when I can simply use enumerate()?

Is it a couple orders of magnitude faster?

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


Where to find Visual Studio Syntax Highlighting (for python)?

2008-06-06 Thread Robert Dailey
Hi,

Does anyone know of a way to get syntax coloring working in Visual Studio
2008 for Python? I did some googling but I couldn't find anything. Help is
appreciated, thank you.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Do this as a list comprehension?

2008-06-06 Thread John Salerno
"Terry Reedy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> "Mensanator" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]

> Which is exactly the purpose of zip, or its specialization enumerate!

Thanks guys! Looks like the simplest is always the best yet again! :) 


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


noob question : library versus normal python files

2008-06-06 Thread ravinder thakur
hello friends,


i have a python library(rdflib) that i am using in some project using
Google App Engine. I have developed everything using this on my local
machine and things work fine. But in my final deployment, i have to
use it in source code form rather than in library form. If i remove
the library and start using the source code, thing are just not
working even if i append the dir of source to the python path. any
ideas on how to use the source code for a python library rather than
using the library itself ?


i tried googling any good tutorial for python libraries but couldn't
find one. can someone share a link or something similar ?


thanks
ravinder thakur
--
http://mail.python.org/mailman/listinfo/python-list


ctypes help

2008-06-06 Thread gianluca
hy,
I've a huge problem with ctypes. I've compiled my C library and I'd
like use it in python with ctype. One function need to pass a pointer
to typed ( like this: typedef int value_type). In python I can access
to that funtion but arise an exception  because python don't know my
value_type typedef.

Please I need help, could anybody help me?

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


Re: lots of futex_wait calls

2008-06-06 Thread André Malo
skunkwerk wrote:

> I've got a python program written for the django web framework that
> starts about 100 threads.  When I start the server, it sometimes eats
> up 100% of the CPU for a good minute or so... though none of the
> threads are CPU-intensive
> 
> doing a strace on the program, i found lots of calls like this:
> 
> select(5, [4], [], [], {1, 0}) = 0 (Timeout)
> futex(0x86a3ce0, FUTEX_WAIT, 0, NULL) = 0
> 
> i've read the man page for futex... but is this normal?

More or less. Most of the futex calls (if not all) are grabbing or releasing
the global interpreter lock (GIL).

It's usually helpful to increase the thread-schedule-checkinterval in order
to lessen the system load (especially the number of context switches). See
sys.setcheckinterval.

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


Re: How to remove read-only from a file

2008-06-06 Thread Robert Dailey
On Fri, Jun 6, 2008 at 11:05 AM, Tim Golden <[EMAIL PROTECTED]> wrote:

> Robert Dailey wrote:
>
>> Hi,
>>
>> Using Python 3.0, how can I remove a read-only property from a file in
>> Windows XP? Thanks.
>>
>
> import os
> import stat
>
> os.chmod ("c:/temp/temp.txt", stat.S_IWRITE)
>
> (Haven't actually checked that on Python 3.0 but I don't believe
> it's changed...)


Works great, thank you!
--
http://mail.python.org/mailman/listinfo/python-list

The best sexy video and photo!!!

2008-06-06 Thread sexy18
http://rozrywka.yeba.pl/show.php?id=2737
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to kill a thread?

2008-06-06 Thread Diez B. Roggisch

Laszlo Nagy schrieb:




def run(self):
while True:
if exit_event.isSet():
# Thread exiting
return
try:
data = q_in.get(timeout = .5)
except Queue.Empty:
continue
# ... process data
 
And then in the MainThread I do exit_event.set() and wait for all 
threads to exit. It's a pretty awkward solution but works.


BTW Guys, is something like Thread.kill() planned for the future? Or 
is there a reason not to have it?
Python threads are cooperative. I think there was a discussion about 
this, about a year ago or so. The answer was that in CPython, the 
interpreter has this GIL. Python threads are always running on the same 
processor, but they are not "native". There are operating system 
functions to kill a thread but you must not use them because it can 
crash the interpreter. 


This is not correct. Neither are threads cooperative nor are they not 
native. If they weren't cooperative they needed explicit re-scheduling 
statements in the code. And they also are based on native OS threads.


They might *appear* not cooperative if a long-running C-call doesn't 
release the GIL beforehand.


This of course doesn't affect other parts of your reasoning about 
killing threads being a bad idea and such.


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


lots of futex_wait calls

2008-06-06 Thread skunkwerk
I've got a python program written for the django web framework that
starts about 100 threads.  When I start the server, it sometimes eats
up 100% of the CPU for a good minute or so... though none of the
threads are CPU-intensive

doing a strace on the program, i found lots of calls like this:

select(5, [4], [], [], {1, 0}) = 0 (Timeout)
futex(0x86a3ce0, FUTEX_WAIT, 0, NULL) = 0

i've read the man page for futex... but is this normal?

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


SWIG -- Passing python proxy class instance to python callback

2008-06-06 Thread Keith Sabine

Hi

Did you ever find a solution to this? I am having the exact same problem...

- Keith

I'm trying to pass a proxy class instance (SWIG generated) of CClass,
to a python callback function from C++.  The proxy class instance of
CClass is created from a pointer to the C++ class CClass.

Using the code below, I receive the error message:

"AttributeError: 'PySwigObject' object has no attribute 'GetName'"


The python callback function is being passed in through the clientdata
pointer, and the CClass *class pointer is what's being converted to an
instance of the SWIG proxy class and passed to the python callback
function as an argument.

static void PythonCallBack(CClass *class,void *clientdata)
{
  PyObject *func, *arglist,*obj;
  PyObject *result;

  func = (PyObject *) clientdata;   // Get Python function
  obj = SWIG_NewPointerObj((void*) cmd, SWIGTYPE_p_CSCSICommand,  1);
//create instance of python proxy class from c++ pointer

  arglist=Py_BuildValue("(O)",*obj); //convert to tuple
  result = PyEval_CallObject(func,arglist); // Call Python

  Py_XDECREF(result);
  return;
}

Any input would greatly appreciated.  Thanks,
Jeff


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


Re: ClassName.attribute vs self.__class__.attribute

2008-06-06 Thread David C. Ullrich
In article <[EMAIL PROTECTED]>,
 Gabriel Rossetti <[EMAIL PROTECTED]> wrote:

> Larry Bates wrote:
> > Gabriel Rossetti wrote:
> >> Hello everyone,
> >>
> >> I had read somewhere that it is preferred to use 
> >> self.__class__.attribute over ClassName.attribute to access class 
> >> (aka static) attributes. I had done this and it seamed to work, until 
> >> I subclassed a class using this technique and from there on things 
> >> started screwing up. I finally tracked it down to 
> >> self.__class__.attribute! What was happening is that the child 
> >> classes each over-rode the class attribute at their level, and the 
> >> parent's was never set, so while I was thinking that I had indeed a 
> >> class attribute set in the parent, it was the child's that was set, 
> >> and every child had it's own instance! Since it was a locking 
> >> mechanism, lots of fun to debug... So, I suggest never using 
> >> self.__class__.attribute, unless you don't mind it's children 
> >> overriding it, but if you want a truly top-level class attribute, use 
> >> ClassName.attribute everywhere!

I shouldn't butt in since everyone else knows more about
this than I do, but it seems to me that saying you should
do this is wrong and saying you should do that is wrong -
which you should do depends on what you're trying to
accomplish.

There's something that comes up all the time in stuff
I do, where implicitly accessing self.__class__.attribute
is vital to make it work right. Say I have a Matrix class,
with an __add__ method:

class Matrix:
  def __init__(self, data):
whatever
  def __add__(self, other):
newdata = whatever
return Matrix(newdata)

The last line is almost surely not what I want (took
me a while, long ago, to figure this out). Because someday
when I have a subclass I want __add__ to return an instance
of the subclass. At first I thought I needed to rewrite the
last line to return SubClass(newdata). No, I simply return
self.__class__(newdata) and it works exactly the way I want.

> >> I wish books and tutorials mentioned this explicitly
> >>
> >> Gabriel
> >
> > If you define a class instance variable with the same name as the 
> > class attribute, how would Python be able to distinguish the two?  
> > That is a feature not a problem.  Getter looks for instance attribute, 
> > if one is not found it looks for a class attribute, and upwards.  This 
> > behavior is used by Zope to do all sorts of neat stuff.
> >
> > -Larry Bates
> > -- 
> > http://mail.python.org/mailman/listinfo/python-list
> >
> >
> A class instance variable, you must mean an instance attribute no? If 
> that is so, then with just self.attribute? Maybe there is a concept that 
> I don't know about, I've studied class/static attributes and instance 
> attributes in my OOP classes.
> 
> Gabriel

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


Re: Image Processing (batch)

2008-06-06 Thread Ivan Illarionov
On Thu, 05 Jun 2008 07:10:56 +, Tim Roberts wrote:

> Thomas Guettler <[EMAIL PROTECTED]> wrote:
>>
>>I tried PIL for image batch processing. But somehow I don't like it
>>  - Font-Selection: You need to give the name of the font file. -
>>  Drawing on an image needs a different object that pasting and saving.
>>  - The handbook is from Dec. 2006.

I don't want to dissapoint you but PIL font handling sucks terribly.

> I have repeatedly seen the attitude in your last point, and I simply do
> not understand it.  What on Earth is wrong with having a product that
> actually becomes stable?
> 
> We all complain about Microsoft's feature bloat, rolling out unnecessary
> new releases of their products year after year with features that no one
> really needs.  But when an open source product FAILS to produce a new
> release every six weeks, we start seeing posts questioning whether the
> product is still viable or has become abandonware.

I think if you really TRY to create your own project you'll understand 
what's going on here.

>From near 10 open source projects that I've started only 1 is living 
today.

> Once a product does the job it was designed to do, IT'S DONE.

Because there's no such thing as "do the job you where designed to do"
Example: designed for image manipulation. No matter how many features 
you've already implemented there's always something more to do.

> Personally, I think PIL is a great solution for batch processing, but
> the beauty of the open source world is that the ARE alternatives.

Yes, it's open source, and everybody will win if you'll extend PIL to do 
what you want.

Really, I do have some working snippets of code that do handle fonts 
nicely with PIL images, read and parse OpenType tables, but I can't 
publish it because it's optimized for my private needs like only two 
languages: Russian and English.

I had to rewrite PIL's FreeType layer from scratch to do what I want.

You can do the same.

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


Re: How to remove read-only from a file

2008-06-06 Thread Tim Golden

Robert Dailey wrote:

Hi,

Using Python 3.0, how can I remove a read-only property from a file in
Windows XP? Thanks.


import os
import stat

os.chmod ("c:/temp/temp.txt", stat.S_IWRITE)

(Haven't actually checked that on Python 3.0 but I don't believe
it's changed...)

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


How to remove read-only from a file

2008-06-06 Thread Robert Dailey
Hi,

Using Python 3.0, how can I remove a read-only property from a file in
Windows XP? Thanks.
--
http://mail.python.org/mailman/listinfo/python-list

Re: File-writing not working in Windows?

2008-06-06 Thread jay graves
On Jun 6, 10:18 am, [EMAIL PROTECTED] wrote:

> This code works PERFECTLY in Linux.  Where I have a match in the file
> I'm processing, it gets cut out from the start of the match until the
> end of the match, and written to the temporary file in tempdir.
> It does not work in Windows.  It does not create or write to the
> temporary file AT ALL.  It creates the tempdir directory with no
> problem.

In general, I don't use string concatenation when building paths.
Especially on scripts that are meant to run on multiple platforms.


> Here's the kicker: it works perfectly in Windows if Windows is running
> in VMware on a Linux host!  (I assume that that's because VMware is
> passing some call to the host.)

probably a red herring.

> Can anyone tell me what it is that I'm missing which would prevent the
> file from being created on Windows natively?

Get rid of the 'posix' check and use os.path.join to create
'tempfileName' and see if it works.

HTH.
...
Jay Graves
--
http://mail.python.org/mailman/listinfo/python-list


Re: cgi, parse_header and semi-colon

2008-06-06 Thread Richard Brodie

"Sylvain" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> If we upload a file with a semi-colon (i.e : "C:/my;file.jpg") :
> cgi.FieldStorage.filename returns only "my" everything after the semi-
> colon is missing
>
> Is it a bug or i'm missing something ?

I doubt it's bug in parse_header, since it's meant to split on
semicolons. Whether it's a bug in one of its callers, or the client
not escaping sufficiently, I couldn't say offhand.


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


Re: Newb question: underscore

2008-06-06 Thread Bruno Desthuilliers

John Fabiani a écrit :

Skye wrote:


What is this doing?

print >> fd, _(__doc__)


I'm guessing line-splitting __doc__ into a list, but what's that
leading underscore do?

Thanks!

I think it is standard practice to use the underscore for unicode converts.


Actually, it's for i18n, not for encoding.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newb question: underscore

2008-06-06 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

My question is: Why would anyone decide to obfuscate something as easy
to read as Python???

They didn't decide to obfuscate; they decided to follow a
strongly-expected convention for the name of that function by existing
users of the 'gettext' functionality, in contexts that predate the
appearance of that functionality in Python.



Well _ can also mean the previous output statement that wasn't null,


In the shell only IIRC.

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


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread Bruno Desthuilliers

Russ P. a écrit :

On Jun 5, 2:27 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

On Thu, 5 Jun 2008 11:36:28 -0700 (PDT), "Russ P."
<[EMAIL PROTECTED]> declaimed the following in comp.lang.python:


would need to use a "mangled" name to access private data or methods.
But you will be using the name many times, you can reassign your own
name, of course, so the mangled name need not appear more than once
where it is needed.

Which will break the first time the "innards" rebind a value to the
mangled name, as the "simplified" external name will still be bound to
the previous value.


I'm not sure you understood what I meant. In current Python, if I need
access to data element __XX in class YourClass, I can use
ZZ._YourClass__XX, but if I don't want to clutter my code with that
mangled name, I can just write

XX = ZZ._YourClass__XX

and refer to it from that point on as XX. 

>

Obviously if the meaning of
__XX changes within class ZZ, this will break, but that's why you are
supposed to avoid using private data in the first place.


AFAICT, What Dennis meant is that the binding of ZZ._YourClass__XX 
changes between the moment you bind it to local XX and the moment you 
use it, then you're out.

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


Re: parser recommendation

2008-06-06 Thread Kay Schluehr
On 6 Jun., 01:58, Alan Isaac <[EMAIL PROTECTED]> wrote:
> One other possibility:
> SimpleParse (for speed).
> http://simpleparse.sourceforge.net/>
> It is very nice.
> Alan Isaac

How does SimpleParse manage left-factorings, left-recursion and other
ambiguities?

For example according to [1] there are two non-terminals

UNICODEESCAPEDCHAR_16

and

UNICODEESCAPEDCHAR_32

with an equal initial section of 4 token. How does SimpleParse detect
when it has to use the second production?

[1] http://simpleparse.sourceforge.net/simpleparse_grammars.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread Bruno Desthuilliers

Russ P. a écrit :

On Jun 5, 4:53 am, Bruno Desthuilliers  wrote:

Russ P. a écrit :



Given your very recent discovery of what 'dynamic' *really* means in
Python (like, for exemple, dynamically adding / replacing attributes -
including methods - on a per-class or per-instance basis), possibly, yes.


My "very recent" discovery? Funny, I thought I knew that several years
ago. 


Looks like I mistook your
"""
I also realize, by the way, that Python allows a client of a class to
define a new class member from completely outside the class
definition
"""

as "I just realized (...)"

Sorry for having read too fast.


I also realize, by the way, that Python allows a client of a class to
define a new class member from completely outside the class
definition. Obviously, that cannot be declared private.

Why so ?


Why should the client of a class not be able to declare a *private*
member of the class? You're kidding, right?


I'm dead serious. I often add implementation attributes to either a 
class or an instance. These *are* implementation parts, not API.



Do you mind if I tell you
how to arrange the furniture in your bedroom?


I must be a bit dumb, but I don't see how human interaction problems 
relate to enforced access restriction in an OO programming language.



But if the
same identifier is already declared private within the class, than the
new definition should not be allowed (because it would defeat the
whole idea of "private" class members).

Why so ?

Metaprogramming (including monkeypatching) is part of the pythoneer's
toolbox, and while it's not something to use without pretty good
reasons, it has many times proven to be a real life saver. In languages
not allowing it, the solutions to the class of problems easily solved by
monkeypatching happens to be at best a kludge, at worst plain
unsolvable, at least without too much effort to be even worth it. Your
above proposition would arbitrarily make possible and useful things
either uselessly complicated or near impossible.


For the record, I have made it abundantly clear that I don't think
Python should not have as rigorous an encapsulation regime as C++ or
Java. The worst that could happen with my proposition is that you
would need to use a "mangled" name to access private data or methods.


That's already the case - when you use __name_mangling. And if there's 
no effective access restriction, then what the point of having this 
'priv' keyword ?



But you will be using the name many times, you can reassign your own
name, of course, so the mangled name need not appear more than once
where it is needed.


Once again, I just don't see the point. Either you want effective access 
restriction in Python, or you don't. And if you don't, what would this 
'priv' keyword be useful to ?

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


File-writing not working in Windows?

2008-06-06 Thread tdahsu
All,

I have the following code:
   for fileTarget in dircache.listdir("directory"):
(dirName, fileName) = os.path.split(fileTarget)
f = open(fileTarget).readlines()
copying = False
for i in range(len(f)):
for x in range (0,24,1):
if (re.search(self.Info[x][3], f[i])):
#If we have a match for our start of section...
if (self.Info[x][2] == True):
#And it's a section we care about...
copying =
True  #Let's start copying the lines out
to the temporary file...
if (os.name == "posix"):
if (self.checkbox25.GetValue() ==
False):
tempfileName = "tempdir/" +
self.Info[x][0] + "_tmp_" + fileName + ".txt"
else:
tempfileName =
self.textctrl07.GetValue() + "/" + self.Info[x][0] + "_xyz.txt"
else:
if (self.checkbox25.GetValue() ==
False):
tempfileName = "tempdir\\" +
self.Info[x][0] + "_tmp_" + fileName + ".txt"
else:
tempfileName =
self.textctrl07.GetValue() + "\\" + self.Info[x][0] + "_xyz.txt"
else:
copying = False
if (re.search(self.Info[x][4], f[i])):
#Now we've matched the end of our section...
copying =
False #So let's stop copying out to
the temporary file...
if (copying == True):
g = open(tempfileName,
'a') #Open that file in append mode...
 
g.write(f[i])   #Write the line...
g.close()

This code works PERFECTLY in Linux.  Where I have a match in the file
I'm processing, it gets cut out from the start of the match until the
end of the match, and written to the temporary file in tempdir.

It does not work in Windows.  It does not create or write to the
temporary file AT ALL.  It creates the tempdir directory with no
problem.

Here's the kicker: it works perfectly in Windows if Windows is running
in VMware on a Linux host!  (I assume that that's because VMware is
passing some call to the host.)

Can anyone tell me what it is that I'm missing which would prevent the
file from being created on Windows natively?

I'm sorry I can't provide any more of the code, and I know that that
will hamper your efforts in helping me, so I apologise up front.

Assumptions:
You can assume self.checkbox25.GetValue() is always false for now, and
self.Info[x][0] contains a two character string like "00" or "09" or
"14".  There is always a match in the fileTarget, so self.Info[x][2]
will always be true at some point, as will self.Info[x][4].  I am
cutting an HTML file at predetermined comment sections, and I have
control over the HTML files that are being cut.  (So I can force the
file to match what I need it to match if necessary.)

I hope however that it's something obvious that a Python guru here
will be able to spot and that this n00b is missing!

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


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread Bruno Desthuilliers

Russ P. a écrit :

On Jun 4, 4:29 am, NickC <[EMAIL PROTECTED]> wrote:

On Jun 4, 4:09 am, "Russ P." <[EMAIL PROTECTED]> wrote:


What is it about leading underscores that bothers me? To me, they are
like a small pebble in your shoe while you are on a hike. Yes, you can
live with it, and it does no harm, but you still want to get rid of it.

With leading underscores, you can see *at the point of dereference*
that the code is accessing private data. With a "this is private"
keyword you have no idea whether you're accessing private or public
data, because the two namespaces get conflated together.


That is true. But with the "priv" keyword you'll discover quickly
enough that you are trying to access private data (as soon as you run
the program).


With the current convention, you don't even have to run the program - as 
soon as you *type* the name, you know you're accessing implementation stuff.



And even if a "priv" keyword is added, you are still
free to use the leading underscore convention if you wish.


What does this "priv keyword" buy you then ? Seriously ?


The idea of being able to discern properties of an object by its name
alone is something that is not normally done in programming in
general. 


Want to talk about the hungarian notation that is everywhere in MS 
Windows code ?-) or about the so common C++ coding guideline that 
insists on prefixing "data members" with a m_ or a w_ ?-)


More seriously: yes, you usually try to convey something about some 
relevant properties of the object in the identifier. Like, you know, 
using plurals for collections. Or i, j as loop indices.



Yes, of course you should choose identifiers to be
descriptive of what they represent in the real world, but you don't
use names like "intCount," "floatWeight," or "MyClassMyObject" would
you? 


Nope.


Why not?


Because the naming convention for variables is all_lower_with_underscores.

Also, because 'count' is likely enough to be an integer and 'weight' 
likely enough to be a float - and else another numeric. While 'counts' 
and 'weights' are likely enough to be collections (likely lists) of 
resp. integers and floats.

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


Re: ClassName.attribute vs self.__class__.attribute

2008-06-06 Thread Bruno Desthuilliers

Gabriel Rossetti a écrit :

Larry Bates wrote:

Gabriel Rossetti wrote:

Hello everyone,

I had read somewhere that it is preferred to use 
self.__class__.attribute over ClassName.attribute to access class 
(aka static) attributes. I had done this and it seamed to work, until 
I subclassed a class using this technique and from there on things 
started screwing up. I finally tracked it down to 
self.__class__.attribute! What was happening is that the child 
classes each over-rode the class attribute at their level, and the 
parent's was never set, so while I was thinking that I had indeed a 
class attribute set in the parent, it was the child's that was set, 
and every child had it's own instance! Since it was a locking 
mechanism, lots of fun to debug... So, I suggest never using 
self.__class__.attribute, unless you don't mind it's children 
overriding it, but if you want a truly top-level class attribute, use 
ClassName.attribute everywhere!


I wish books and tutorials mentioned this explicitly

Gabriel


If you define a class instance variable with the same name as the 
class attribute, how would Python be able to distinguish the two?  
That is a feature not a problem.  Getter looks for instance attribute, 
if one is not found it looks for a class attribute, and upwards.  This 
behavior is used by Zope to do all sorts of neat stuff.


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


A class instance variable, you must mean an instance attribute no? 


I think that's what he meant, yes.

If 
that is so, then with just self.attribute? Maybe there is a concept that 
I don't know about, 


The concept of name resolution (aka lookup) rules in Python, perhaps ? 
When you do obj.attribute, attribute is first looked for in the object, 
then in it's class, then in the parent classes. So yes, you can get a 
class (or parent class) attribute directly on the instance. Note that 
assignment on the instance (obj.attribute = value) will alway (computed 
attributes or other hooks excepted) create the attribute on the target, 
so if you have Class.attribute set, and then do obj = Class(); 
obj.attribute = 42, then obj.attribute will shadow Class.attribute.


I've studied class/static attributes and instance 
attributes in my OOP classes.


Forget about your OOP classes, mostly if it was in fact a Java or C++ 
class. Python's object model is very far away from what most courses 
present as "OOP".



Gabriel

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


Re: ClassName.attribute vs self.__class__.attribute

2008-06-06 Thread Bruno Desthuilliers

Hrvoje Niksic a écrit :

"[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
writes:


On 5 juin, 17:40, Gabriel Rossetti <[EMAIL PROTECTED]>
wrote:

Hello everyone,

I had read somewhere that it is preferred to use
self.__class__.attribute over ClassName.attribute to access class (aka
static) attributes.

It's even prefered to use self.attribute,


I was going to write exactly that, but it occurred to me that he might
want to be *assigning* to self.__class__.attribute (or
HisClass.attribute) from his methods, in which case self.attribute
would be quite different.


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


Re: Partial download with ftplib and retrbinary

2008-06-06 Thread Giampaolo Rodola'
On 24 Mag, 12:53, [EMAIL PROTECTED] wrote:
> I am breaking/interrupting my connection with theftpserver at
> present when doing a partial download of a file. I have a callback
> with retrbinary that raises an exception and ends the download. The
> problem is that the server is not notified and hangs. I cannot send
> any further commands and need to relogin to download further. Is there
> a way to still continue downloading without having to login again.
>
> My retrbinary function is:
>
> ftp.retrbinary('RETR '+file, handleDownload,1,bound[0])
>
> where bound[0] is an integer specifying the start byte of the
> download.
>
> My callback is:
>
> def handleDownload(block):
>     global count,localfile,number
>     localfile.write(block)
>     if count==number:
>             raise(Exception)
>     count=count+1
>
> where number specifies the number of bytes to download.
>
> Help would be gratefully received.

The server hangs on because the data connection is left open.
Unfortunately you have no easy way to close the data connection by
using retrbinary.
You have to trick a little bit and keep a reference of the data socket
and manually close it.
The example below starts to retrieve a file and stops when 524288
bytes have been received.
Hope this could help you.


import ftplib
ftp = ftplib.FTP('127.0.0.1', 'user', 'password')
ftp.voidcmd('TYPE I')
conn = ftp.transfercmd('RETR filename') # the data socket
bytes_recv = 0
while 1:
chunk = conn.recv(8192)
# stop transfer while it isn't finished yet
if bytes_recv >= 524288: # 2^19
break
elif not chunk:
break
file.write(chunk)
bytes_recv += len(chunk)
conn.close()


--- Giampaolo
http://code.google.com/p/pyftpdlib
--
http://mail.python.org/mailman/listinfo/python-list


Re: Proof that \ is a better line joiner than parenthetical sets

2008-06-06 Thread Jordan Greenberg

Joshua Kugler wrote:

"Beautiful is better than ugly."
And I think putting parenthesis around a multi-line statement is much
prettier.

So there! :)

j


And PEP 8 agrees with you. Another vote for parens.

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


Re: creating yaml without tags using pyyaml

2008-06-06 Thread Stephen Moore
On Fri, Jun 6, 2008 at 8:20 PM, Kirill Simonov <[EMAIL PROTECTED]> wrote:
> Stephen Moore wrote:
>>
>> I have come to the conclusion that this is the fault of the tags (for
>> example, !!python/tuple) as getting rid of them gets rid of the
>> errors.
>>
>> So I'm wondering if there is an option to YAML.decode that will create
>> a yaml document without the tags?
>
> Try yaml.safe_dump().
>
 import yaml
>
 print yaml.dump(())
> !!python/tuple []
>
 print yaml.safe_dump(())
> []
>
>
> Thanks,
> Kirill
>

yes, that's exactly what I wanted :)

however it still caused problems...

but I've managed to make it so it doesn't use tuples and now it all
seems to work.

thankyou for your help anyways, it's greatly appreciated :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to kill a thread?

2008-06-06 Thread Laszlo Nagy




def run(self):
while True:
if exit_event.isSet():
# Thread exiting
return
try:
data = q_in.get(timeout = .5)
except Queue.Empty:
continue
# ... process data
 
And then in the MainThread I do exit_event.set() and wait for all 
threads to exit. It's a pretty awkward solution but works.


BTW Guys, is something like Thread.kill() planned for the future? Or 
is there a reason not to have it?
Python threads are cooperative. I think there was a discussion about 
this, about a year ago or so. The answer was that in CPython, the 
interpreter has this GIL. Python threads are always running on the same 
processor, but they are not "native". There are operating system 
functions to kill a thread but you must not use them because it can 
crash the interpreter. Python MUST clean up object reference counts, 
manage memory etc. The OS function would kill the thread in a way so 
that it would be impossible to fee up memory, and also the interpreter 
can be left in bad state.


I'm not sure about the details, but the short answer is that it is not 
planned. Many programmers said that you have to write cooperative 
threads anyway. Killing threads forcedly is not a good idea in any language.


I hope others will correct me if I'm wrong.

Best,

  Laszlo

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


cgi, parse_header and semi-colon

2008-06-06 Thread Sylvain
Hi,

I'm playing with Google App Engine and during my tests it seems that
there is a bug in cgi. parse_header function.

If we upload a file with a semi-colon (i.e : "C:/my;file.jpg") :
cgi.FieldStorage.filename returns only "my" everything after the semi-
colon is missing

Is it a bug or i'm missing something ?

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


Re: configure fails

2008-06-06 Thread A.T.Hofkamp
On 2008-06-05, Mathieu Prevot <[EMAIL PROTECTED]> wrote:
> I have the following error on a OSX.5 OS with CC=icc and using the
> python-svn files:
>
> checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t)
>
> I would like to help so we can compile python with icc/OSX.

This looks like a autoconf bug (./configure is normally created by autoconf)
.
You should check whether this wchar_t configure computation is part of the
standard autoconf macro's or a Python-project specific autoconf macro.

Then fix the problem and supply a patch to the right community.

You may want to subscribe to some autoconf mailing list

Sincerely,
Albert

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


Re: Python CGI Upload from Server Status

2008-06-06 Thread Derek Tracy
On Fri, Jun 6, 2008 at 9:16 AM, John Dohn <[EMAIL PROTECTED]> wrote:

> On Sat, Jun 7, 2008 at 12:50 AM, Derek Tracy <[EMAIL PROTECTED]> wrote:
>
>> I am trying to create a simple python cgi app that allows the user to kick
>> off an ftp from the server the cgi is on to another server; I have that
>> piece working using ftplib but since the files in question are usually very
>> large (500mb to 2gb) in size I want to be able to display some sort of
>> status to the user, preferrably a progress bar of some sort.
>
>
> You'll need some AJAX progress bar (hint: google for this term ;-) that
> will be getting updates from the server or request an update every second or
> so.
>
> The question is if your upload code can provide progress tracking? If it's
> just a call to some xyz.upload("/here/is/my-500M-file.bin") that only
> returns after several minutes of uploading without giving you any updates on
> how fast things go you're probably out of luck.
> OTOH if it can do e.g.callbacks for progress reporting or if it can run in
> a separate thread that you could query somehow you can hook that to that
> AJAX thing of your choice.
>
> JDJ
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I will look for the AJAX Progress Bar, but I will admit I have never touched
AJAX and haven't written javascript in years.

I patched Pythons ftplib.py storbinary() to send callbacks to the specified
method, so I have the callbacks locked down.  The thing to note is that this
app isn't allowing the user to upload to the server the cgi is on but rather
allowing the user to kick off an ftp process on the server to another
server.

Would there be a way to do this with python cgi and automatically append or
update information on the page it is displaying?

-- 
-
Derek Tracy
[EMAIL PROTECTED]
-
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python CGI Upload from Server Status

2008-06-06 Thread John Dohn
On Sat, Jun 7, 2008 at 12:50 AM, Derek Tracy <[EMAIL PROTECTED]> wrote:

> I am trying to create a simple python cgi app that allows the user to kick
> off an ftp from the server the cgi is on to another server; I have that
> piece working using ftplib but since the files in question are usually very
> large (500mb to 2gb) in size I want to be able to display some sort of
> status to the user, preferrably a progress bar of some sort.


You'll need some AJAX progress bar (hint: google for this term ;-) that will
be getting updates from the server or request an update every second or so.

The question is if your upload code can provide progress tracking? If it's
just a call to some xyz.upload("/here/is/my-500M-file.bin") that only
returns after several minutes of uploading without giving you any updates on
how fast things go you're probably out of luck.
OTOH if it can do e.g.callbacks for progress reporting or if it can run in a
separate thread that you could query somehow you can hook that to that AJAX
thing of your choice.

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

Re: BZip2 decompression and parsing XML

2008-06-06 Thread Stefan Behnel
phasma wrote:
> xml.parsers.expat.ExpatError: not well-formed (invalid token): line
> 538676, column 17

Looks like your XML file is broken in line 538676.


> try:
> handler = open(args[0], "r")

This should read

  handler = open(args[0], "rb")

Maybe that's your problem.

BTW, since you seem to parse a pretty big chunk of XML there, you should
consider using lxml. It's faster, more memory friendly, more feature-rich and
easier to use than minidom. It can also parse directly from a gzip-ed file or
a file-like object as provided by the bz2 module.

http://codespeak.net/lxml/

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


BZip2 decompression and parsing XML

2008-06-06 Thread phasma
Hi.

I'm trying to disassemble bzipped file. If I use minidom.parseString,
I'm getting this error:

Traceback (most recent call last):
  File "./replications.py", line 342, in ?

  File "/usr/lib64/python2.4/xml/dom/minidom.py", line 1925, in
parseString
return expatbuilder.parseString(string)
  File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 940, in
parseString
return builder.parseString(string)
  File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 223, in
parseString
parser.Parse(string, True)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line
538676, column 17

If I use minidom.parse, I'm getting this error:

Traceback (most recent call last):
  File "./replications.py", line 341, in ?
files.xml = minidom.parse(bz2.decompress(dump))
  File "/usr/lib64/python2.4/xml/dom/minidom.py", line 1915, in parse
return expatbuilder.parse(file)
  File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 922, in
parse
fp = open(file, 'rb')
IOError

But XML parsed normally.

Code:

try:
handler = open(args[0], "r")
dump = handler.read()
handler.close()
except IOError, error:
print("Can't open dump: %s" % error)
sys.exit(1)

files.xml = minidom.parse(bz2.decompress(dump))

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


Re: creating yaml without tags using pyyaml

2008-06-06 Thread Kirill Simonov

Stephen Moore wrote:

I have come to the conclusion that this is the fault of the tags (for
example, !!python/tuple) as getting rid of them gets rid of the
errors.

So I'm wondering if there is an option to YAML.decode that will create
a yaml document without the tags?


Try yaml.safe_dump().

>>> import yaml

>>> print yaml.dump(())
!!python/tuple []

>>> print yaml.safe_dump(())
[]


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


  1   2   >