Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Stefano Masini
On 10 Sep 2005 02:10:59 EDT, Tim Daneliuk <[EMAIL PROTECTED]> wrote:
> As someone who implemented their own configuration mini-language
> with validation, blah, blah, blah 
> (http://www.tundraware.com/Software/tconfpy/)

Well, a configuration mini language with validation and blahs is not
exactly what I would call _simple_... :) so maybe it doesn't even fit
into my idea of testing-stdlib, or "quick and dirty" section of the
manual (see my other post).
But certainly it would be worth mentioning in the list of available
solutions under the subsection "Configuration files handling".

> 1) The existing tool is inadequate for the task at hand and OO subclassing
> is overrated/overhyped to fix this problem.  Even when you override
> base classes with your own stuff, you're still stuck with the larger
> *architecture* of the original design.   You really can't subclass
> your way out of that, hence new tools to do old things spring into
> being.

That's true, but usually only when the original design if too simple
comparing to the complexity of the problem. Instead a very general
solution can usually be subclassed to easily handle a simpler problem.
You still have to actually understand the general and complex design
in order to be able to write subclasses, so maybe one can be tempted
to punt on it, and write its own simple solution. But in this case it
would just be enough to propose a few solutions in the testing-stdlib:
a) one simple implementation for simple problems, easy to understand,
but limited.
b) one complex implementation for complex problems, 
c) one simplified implementation for simple problems, easy to
understand, but subclassed from a complex model, that leaves room for
more understanding and extension just in case one needs more power.

I fully understand the difficulty of reusing code, as it always forces
you to a learning curve and coming to compromises. But I've also
wasted a lot of time reinventing the wheel and later found stuff I
could have happily lived with if I only had known.

> 2) It's a learning exercise.

Well, so we might as well learn a little more and rewrite os.path, the
time module and pickle. Right? :)

> 3) You don't trust the quality of the code for existing modules.
> (Not that *I* have this problem :-p  but some people might.)

That's a good point, but it really boils down to being a wise
programmer on one side, being able to discern the Good from the Bad,
and an active community on the other side, able to provide good
solutions and improve them.
If either one is missing, then a lot of bad stuff can happen, and we
can't really take community decisions basing on the assumption that
programmers won't be able to understand, or that the community won't
be able to provide. So we might as well assume that we have good
programmers and an active community.
Which I think is true, by the way!
So, let's talk about a way to more effectively present available
solutions to our good programmers! :)

cheers,
stefano
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nested tuples

2005-09-09 Thread Tim Roberts
"Luis P. Mendes" <[EMAIL PROTECTED]> wrote:
>
>I'm trying to solve this problem:
>
>suppose I'm reading a csv file and want to create a tuple of all those
>rows and values, like ((row1value1, row1value2, row1value3),(row2value1,
>row2value2, row2value3),..., (rowNvalue1, rowNvalue2, rowNvalue3))
>
>I haven't found the way to do it just using tuples.  How can I do it?
>
>Nevertheless, I can solve it like this:
>a=[]
>
>for row in reader:
>~   elem = (row[0],row[1],row[2])
>~   a.append(elem)
>
>which will result in a list of tuples: [(row1value1, row1value2,
>row1value3),(row2value1, row2value2, row2value3),..., (rowNvalue1,
>rowNvalue2, rowNvalue3)]
>
>Then, I get what I want with tuple(a).

Why?  What is it about the list of tuples that you don't like?
Philosophically, it's more in line with Guido's separation of list and
tuple.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python compiled?

2005-09-09 Thread Tim Roberts
"billiejoex" <[EMAIL PROTECTED]> wrote:
>
>Hi all. I'm sorry for a noob question like this but I'll try to ask it 
>anyway.
>One of the greatest problem that may discourage a new user to choose Python 
>language is it's interpreted nature.

I doubt it.  C#, VB.NET, VBscript, Javascript and Perl have not suffered
from being interpreted.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Tim Daneliuk
Stefano Masini wrote:



> I wonder how many people (including myself) have implemented their own
> versions of such modules, at least once in their pythonic life. I
> indeed have my own odict (even same name! :). My own pathutils
> (different name, but same stuff). My own validate... and so forth.

As someone who implemented their own configuration mini-language
with validation, blah, blah, blah (http://www.tundraware.com/Software/tconfpy/)
I can give you a number of reasons - all valid for different people at
different times:

1) The existing tool is inadequate for the task at hand and OO subclassing
is overrated/overhyped to fix this problem.  Even when you override
base classes with your own stuff, you're still stuck with the larger
*architecture* of the original design.   You really can't subclass
your way out of that, hence new tools to do old things spring into
being.

2) It's a learning exercise.

3) You don't trust the quality of the code for existing modules.
(Not that *I* have this problem :-p  but some people might.)


-- 

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Stefano Masini
On 9/9/05, Dave Brueck <[EMAIL PROTECTED]> wrote:
> shot). The cost of developing _exactly_ what you need often is (or at least
> *appears* to be) the same as or lower than bending to use what somebody else 
> has
> already built.

That's right. But as you say, this is _often_ the case, not always.
One doesn't necessarily need to "bend" too much in order to use
something that's available out there.
If we're talking about simple stuff, like ordered dictionaries, file
system management, ini files roundtripping, xml serialization (this
one maybe is not that trivial...), I don't think you would have to
come to big compromises.

I myself reinvented these wheels a few times in different projects,
because I wasn't happy with the way I reinvented the first time, then
I eventually found some code written by someone else that was
_exactly_ the same as my last attempt, my most evolved and "perfect",
my presciou :), if it wasn't even better. Separate paths of
evolution that converged to the same solution, because the problem was
simple to begin with. Under this light, it seems to me that I wasted a
lot of time. If odict was in the stdlib I wouldn't have bothered
writing it.

And yet, this code is not available in the stdlib. Sometimes it's not
even trivial to be googled for. Plus, if you think of a python
beginner, what's the chance that he's gonna say: naa, this code in the
library sucks. I'm gonna search google for another ini file round
tripper. Whatever is available there, he's gonna use, at least in the
beginning. Then he will soon figure out that it indeed sucks, and at
that point there's a chance that he'll say: man... _python_ sucks! I
cannot even round trip an ini file with the same module!

That's why I say this lack of a centralized, officially recommended
code repository maybe is hurting python.

I agree that building library code is hard because it has to be both
correct and simple. But, again, there's a lot of useful stuff not the
library, that's simple in the start so it's just a matter of writing
it correctly. If the semantics can be different, just provide a couple
of alternatives, and history will judge.

It would be great if there was a section in the Python manual like this:

"Quick and Dirty: Commonly needed tricks for real applications"

1. odict
2. file system management
3. xml (de)serialization
4. ...

Each section would describe the problem and list one or a few
recommended implementations. All available under __testing_stdlib__.
Appoint somebody as the BDFL and make the process of updating the
testing stdlib democratic enough to allow for more evolution freedom
than the stable stdlib.

If such a "quick and dirty" section existed, I think it would also
become a natural randevouz point for innovators. If one invented a new
cool, simple and useful module, rather than just publishing it in his
own public svn repository, he would feel comfortable to start a
discussion on the python-testing-stdlib mailing list suggesting to
include it in the "quick and dirty" section of the manual. The manual
is the primary resource that every python programmer makes use of,
expecially beginners. But it is so official that no one would ever
dare suggesting to include something in it. If the Vaults of Parnassus
were listed in there (maybe a bit trimmed and evaluated first ;) a
beginner would have immediate access to the most common tricks that
one soon faces when it comes to writing real applications.

I'm talking wildly here... I'm quite aware of how simplistic I made it.
Just throwing an idea.

What do you think?

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


Re: Yielding a chain of values

2005-09-09 Thread [EMAIL PROTECTED]
I'm not really worry that much over O(n^2) performace (especially
having optimized some O(n^3) SQL operations :-o !)

The things is this really should be an O(n) operation. Having a yield
all statement or expression is useful in its own right and also
potentially a way to optimized away the O(n^2) issue.

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


Re: python object model diagram

2005-09-09 Thread Peter Hansen
gene tani wrote:
> I think he's looking for tidy pictures of how metaclasses and
> descriptors interact with your classes and instances at compile- &
> runtime, something like that (which I haven't seen)
> 
> There's pictures of the class hierarchy for C and j-python:
> 
> http://www.brpreiss.com/books/opus7/html/page114.html

Hmm... isn't that just a diagram of one guy's set of classes (Bruce, who 
wrote a book about data structures apparently), not of anything 
particularly specific to Python.  For example, standard Python certainly 
doesn't have any class called MultisetAsLinkedList.

But you could be right that he's looking for a class hierarchy diagram. 
  If so, the question is still "of what classes?".

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


Re: OOP Newb

2005-09-09 Thread James Stroud
Work through the appropriate chapters of this free book:

http://www.ibiblio.org/obp/thinkCSpy/

"How to Think Like a Computer Scientist"

James

On Friday 09 September 2005 18:47, MilkmanDan wrote:
> I've been learning python for a while. It's awesome.  My problem is
> that I don't know anything about object oriented programming.  I can't
> seem to find any tutorials either, everything kind of assumes a basic
> knowledge of the subject.
>
> I have managed to figure out a few things, like what a class and an
> instance are, but I can't figure out how to use oop for anything.  Does
> anyone know where I can find out how to write an object (or anything
> else!) in python, or can anyone explain it to me?

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Design Principles

2005-09-09 Thread Neal Norwitz
[EMAIL PROTECTED] wrote:
>
> But I am still puzzled by the argument that has been given for why
> methods that operate on mutable types should return None, namely, that
> the designers of python didn't want the users to shoot themselves in
> the foot by thinking a method simply returned a result and left the
> data structure unchanged.

Let me try to answer your question with a question.  Given this code:

  >>> d = {}
  >>> e = d.update([(1, 2)])

If .update() returned a dictionary, does d == e?

I'm not sure what you would guess. I am pretty sure that everyone
wouldn't agree whether d should equal e or not.  If they are not equal,
that would mean a new copy would be made on each update which could be
incredibly expensive in speed and memory.  It is also different from
how Python works today, since the update() method mutates the
dictionary.

> In the context of fundamental design principles, if you asked a random
> sample of Python gurus what is more Pythonesque: preventing users from
> shooting themselves in the foot or making things easier to accomplish,
> my impression is that people would overwhelmingly choose the latter.

Probably true, but ...

> After all, the fact that Python is not strongly typed and is
> interpreted rather than compiled gives plenty of ways for people to
> shoot themselves in the foot but what is gained is the abilitity to do
> more with less code.

I think most people programming Python are pretty pragmatic.  There is
no single language that is ideal in all circumstances.  There are
necessarily some trade-offs.  Many believe that tools can help bridge
this gap.  There are at least 2 tools for finding bugs (or gotchas) of
this sort:  pychecker and pylint.

> But in this instance, by not allowing operations on mutable types to
> return the mutated objects, it seems that the other side is being
> taken, sacrificing programmer producitivity for concerns about
> producing possible side effects. It is somewhat ironic, I think, that
> Java, a language whose design principles clearly side on preventing
> users from shooting themselves in the foot, much more so thatn Python,
> generally allows you to get back the mutated object.

I think Python has attempted to create an internal consistency.  I
believe Java has tried to do the same.  However, these aren't the same
sets of consistency.  People are always going to have assumptions.
Python strives to be as intuitive as possible.  However, it can't be
right 100% of the time for all people.

HTH,
n

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


[OT] Re: "grep" database

2005-09-09 Thread Ara . T . Howard
On Fri, 9 Sep 2005, Hilbert wrote:

> Hello,
>
> I've heard of a software on linux that creates a recursive database of
> text files  and then provides an interface for grep-like queries. I'd
> like to use it to find procedures/variables in a large code base.
>
> Any suggestions appreciated.
>
> Thanks,
> Hilbert

google 'glimpse'.

hth.

-a
-- 
===
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| Your life dwells amoung the causes of death
| Like a lamp standing in a strong breeze.  --Nagarjuna
===

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


Re: Create new instance of Python class in C

2005-09-09 Thread phil hunt
On Fri, 9 Sep 2005 18:50:26 +0200, Sybren Stuvel <[EMAIL PROTECTED]> wrote:
>djw enlightened us with:
>> Personally, I would try Psyco first, and consider Pyrex next.
>
>Ok, I'll take a look at those.
>
>> Are you sure your algorithm can't be optimized first, before you
>> start trying to write this in C?
>
>I'm sure there will be optimizations, but profiling showed that the
>copying of the puzzles took the most time. Since the copy.deepcopy()
>function is implemented it Python, I'd thought it would get quite a
>speed boost when done in C instead.

Can you use a different algorithm that doesn't make so many copies?

-- 
Email: zen19725 at zen dot co dot uk


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


Re: Create new instance of Python class in C

2005-09-09 Thread phil hunt
On Fri, 9 Sep 2005 17:19:21 +0200, Sybren Stuvel <[EMAIL PROTECTED]> wrote:
>Hi people,
>
>I'm creating a program that can solve and create Sudoku puzzles. My
>creation function needs to make a lot of copies of a puzzle.

Why do you need to maske lots of copies? And when you say "lots of"
what numbers do you mean? 100? 100?

The reason I ask is I recently wrote a program to solve Sudoku 
puzzles, and IIRC it didn't make copies at all.

-- 
Email: zen19725 at zen dot co dot uk


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


Re: Redundant code in multiple methods

2005-09-09 Thread Sam Pointon
How about using a class, with __call__, as a wrapper instead of the
function itself?


class FunctionWrapper(object):
def __init__(self, cls, function):
self._function = function
self._cls = cls

def __call__(self, *args, **kwargs):
 REQUEST = self.REQUEST
SESSION = REQUEST.SESSION
dbConnection = self._cls.getDBConnection()
logger = self._cls.getLogger()
trackStatsHere()
# set up some local variables here
# change some global variables here
try:
return self._function(self._cls, *args, **kwargs)
except:
raise "handle the error here"
finally:
dbConnection.close()

class User(object):
def __init__(self):
def View(cls, self, localvariables): #Needs the cls argument
before self to take the FunctionWrapper first argument
myHtmlDoc = """make the htmldocument here using all
of the previous variables"""
# play with data here
return myHtmlDoc
self.View = FunctionWrapper(self, View)

def Edit(cls, self): #Ditto
myHtmlDoc = """make the htmldocument here using all
of the previous variables"""
# play with data here
return myHtmlDoc
self.Edit = FunctionWrapper(self, Edit)

#the rest of the class

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


Re: Python linear algebra module -- requesting comments on interface

2005-09-09 Thread Bengt Richter
On Fri, 9 Sep 2005 04:58:43 -0700 (PDT), "C. Barnes" <[EMAIL PROTECTED]> wrote:

>
>Hi, I'm in the process of writing a Python linear
>algebra module.
>
>The current targeted interface is:
>
>  http://oregonstate.edu/~barnesc/temp/linalg/
>
>The interface was originally based on Raymond
>Hettinger's
>Matfunc [1].  However, it has evolved so that now it
>is
>nearly identical to JAMA [2], the Java matrix library.
>
>I am soliticing comments on this interface.
>
>Please post up any criticism that you have.  Even
>small
>things -- if something isn't right, it's better to fix
>it now than later.
>
Wondering whether you will be supporting OpenGL-style matrices and
operations for graphics. UIAM they permit optimizations in both
storage and operations due to the known zero and one element values
that would appear in full matrix representations of the same.

http://www.rush3d.com/reference/opengl-redbook-1.1/appendixg.html

Also wondering about some helper function to measure sensitivity of
.solve results when getting near-singular, but maybe that's an
out-side-of-the package job.

>From a quick look, it looks quite nice ;-)

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


Re: where is sys.path initialized?

2005-09-09 Thread Steve M
The PYTHONPATH environment variable is good for that. For general
customizing beyond the path, you can make a file called:

C:\Python24\Lib\site-packages\sitecustomze.py

and it will be executed every time python runs. It might look like
this:

import sys
sys.path.insert(0, r'C:\Python24\mypython')
sys.setdefaultencoding('latin-1)



Where the tutorial says the sys.path is "initialized from the directory
containing the input script" I think the input script is the file whose
name is the argument to the Python interpreter. E.g., if you ran
"python c:\stuff\myscript.py" then the path is initialized relative to
c:\stuff. If you just run the interpreter in interactive mode, it's
current working directory when you run 'python'. To say that the path
is initialized "from the directory" I guess only matters if any of the
items in PYTHONPATH or the sys.path are not given as absolute pathnames
but rather relative. If my PYTHONPATH has 'mypython' in it with no
absolute qualifier then in the above scenario where I'm in, say, the
c:\windows directory and I run "python c:\stuff\myscript.py" it will be
c:\stuff\mypython that is added to the path. I think...

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


OOP Newb

2005-09-09 Thread MilkmanDan
I've been learning python for a while. It's awesome.  My problem is
that I don't know anything about object oriented programming.  I can't
seem to find any tutorials either, everything kind of assumes a basic
knowledge of the subject.

I have managed to figure out a few things, like what a class and an
instance are, but I can't figure out how to use oop for anything.  Does
anyone know where I can find out how to write an object (or anything
else!) in python, or can anyone explain it to me?

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


Re: "grep" database

2005-09-09 Thread gene tani
maybe look Gonzui, LXR, some of the other tools listed here

http://www.gnu.org/software/global/links.html

Hilbert wrote:
> Hello,
>
> I've heard of a software on linux that creates a recursive database of
> text files  and then provides an interface for grep-like queries. I'd
> like to use it to find procedures/variables in a large code base.
> 
> Any suggestions appreciated.
> 
> Thanks,
> Hilbert

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


Re: python and ARCView GIS desktop

2005-09-09 Thread Andrew MacIntyre
GISDude wrote:
> hi all. I am a newbie, so be kind.
> I am using ARCView GIS 9.1 and python win. I am trying to develop a
> module using the GZIP module in my ARCView map session. What I am
> attempting to do (I think) is use the zip mod to zip up all the files
> in a .mxd document into one neat little zipped file, ready to copy to
> cd or email(if it's small enough(.
> 
> I got this idea while using autocad. There is a function in autocad
> (E-TRANSMIT) that allows you to press the button on the toolbar and it
> will zip up all files(and dependent files too) in the current drawing
> and have it in one zip file ready for email.

I think that ESRI intended that the Map Publisher (extra cost; outputs 
.pmf files as I recall) be used for this purpose.  This is at least 
partly because map documents can contain all sorts of layers that don't 
exist as readily accessible files on your local machine.

> I was wondering if anyone had any ideas. Maybe I could use VBA or
> something else?

If you are only using shapefiles, what you are after should be doable, 
and using VBA is probably the least painful way to do it.  One trap that 
comes to mind is that dataset filenames are stored in .mxds in absolute 
form by default - you will need to change the setting in the normal.mxt 
which enables relative paths. There are examples of creating commands in 
the ArcObjects developers kit (I can't remember whether this is 
installed by default).  You also might be able to use the InfoZip DLL 
directly from VBA to package everything (after you've figured out what 
needs to be packaged).

-
Andrew I MacIntyre "These thoughts are mine alone..."
E-mail: [EMAIL PROTECTED]  (pref) | Snail: PO Box 370
[EMAIL PROTECTED] (alt) |Belconnen ACT 2616
Web:http://www.andymac.org/   |Australia
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python object model diagram

2005-09-09 Thread Ara . T . Howard
On Fri, 9 Sep 2005, gene tani wrote:

> I think he's looking for tidy pictures of how metaclasses and
> descriptors interact with your classes and instances at compile- &
> runtime, something like that (which I haven't seen)
>
> There's pictures of the class hierarchy for C and j-python:
>
> http://www.brpreiss.com/books/opus7/html/page114.html

this is along the lines of what i was asking alright.

> http://www.jython.org/docs/javadoc/overview-tree.html

can one assume this hierarchy maps well to the actual python/c one?  i'd
imagine it's close at least...

thanks for the links!

regards.

-a
-- 
===
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| Your life dwells amoung the causes of death
| Like a lamp standing in a strong breeze.  --Nagarjuna
===

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


Re: python object model diagram

2005-09-09 Thread Mike

I think he's looking for diagrams of the batteries-included modules and 
classes.
My guess is that he thinks there's a set of "framework" classes that is a 
lot deeper and class-ier than it is, similar to what you'd find in C++, C#, 
Java, etc.

So, OP - who won the guessing game :)

m

"gene tani" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I think he's looking for tidy pictures of how metaclasses and
> descriptors interact with your classes and instances at compile- &
> runtime, something like that (which I haven't seen)
>
> There's pictures of the class hierarchy for C and j-python:
>
> http://www.brpreiss.com/books/opus7/html/page114.html
> http://www.jython.org/docs/javadoc/overview-tree.html
>
> , there's pictures of method resolution order in Python Nutshell, (but
> I don't think that's what he's looking for.)
>
> Ara.T.Howard wrote:
>> anyone out there know where i might find a python object model diagram?
>>
> 


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


Re: python object model diagram

2005-09-09 Thread gene tani
I think he's looking for tidy pictures of how metaclasses and
descriptors interact with your classes and instances at compile- &
runtime, something like that (which I haven't seen)

There's pictures of the class hierarchy for C and j-python:

http://www.brpreiss.com/books/opus7/html/page114.html
http://www.jython.org/docs/javadoc/overview-tree.html

, there's pictures of method resolution order in Python Nutshell, (but
I don't think that's what he's looking for.)

Ara.T.Howard wrote:
> anyone out there know where i might find a python object model diagram?
>

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


Re: global variables shared across modules

2005-09-09 Thread Patrick Maupin

MackS wrote:
> print "inside fun(): " + global_var
...
> How can I get the changed value to "persist" in such a way that it
> isn't reset when control leaves fun()? Why is it even reset in the
> first place? After all, the module has already been imported (and the
> initialization of global_var executed) *before* fun() runs, right?
>
> Any clarification and help in solving this would be great

It _does_ persist and it _isn't_ reset.  Try:

import shared
print shared.global_var

at the end of your program, and you will see that you have bound the
identifier global_var in your main program to the same immutable object
that the identifier global_var in shared was bound to, and then you
_changed_ the identifier global_var in shared to point to a different
object.

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


Re: where is sys.path initialized?

2005-09-09 Thread Peter Hansen
Alex wrote:
> No one is answering this question. Why, is it a bit unclear or what?

No, but if you really expected a response in only four hours you need a 
reality check.  Many people don't receive Usenet articles for a day or 
two, possibly longer, and in any case many people don't *check* their 
news more often than once every day or two.

As Robert suggests, have patience.  Generally one should wait several 
days before giving up on a reply.  Reposting is generally less than 
useless (basically it's rude), though reposting with more detail or 
another way of describing your problem is perfectly acceptable.  After a 
day or two...

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


global variables shared across modules

2005-09-09 Thread MackS
Hello everyone

Consider the following two simple files. The first is my "program", the
other a file holding some global variable definitions and code shared
by this program and  a "twin" program (not shown here):

program1.py:


from shared import *

fun()

print "at top level: " + global_var


shared.py:
--

global_var = "original value"

def fun():

global global_var

global_var = "changed value!"

print "inside fun(): " + global_var

return

--

When I run program1.py, I get

inside fun(): changed value!
at top level: original value!

How can I get the changed value to "persist" in such a way that it
isn't reset when control leaves fun()? Why is it even reset in the
first place? After all, the module has already been imported (and the
initialization of global_var executed) *before* fun() runs, right?

Any clarification and help in solving this would be great

Thanks

Mack

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


Re: Re: error processing variables

2005-09-09 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, el chupacabra wrote:

>>Your problem is that the def statement reassignes the name "toHPU" to a
>>function instead of a string.  So when the code runs, you're passing a
>>function object to s.copy2.
> 
>   So...how do fix it?

Don't give two different objects the same name!?

>>> import shutil
>>>
>>> #variables
>>> s = shutil

This can be written as ``import shutil as s`` or maybe you could use
``from shutil import copy2`` to import the `copy2` function into the
moduls namespace.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible improvement to slice opperations.

2005-09-09 Thread Ron Adam
Michael Hudson wrote:
> Ron Adam <[EMAIL PROTECTED]> writes:

>>With current slicing and a negative step...
>>
>>[   1   2   3   4   5   6   7   8   9  ]
>>  -9  -8  -7  -6  -5  -4  -3  -2  -1  -0
>>
>>r[-3:]  ->  [7, 8, 9]# as expected
>>r[-3::-1] ->  [7, 6, 5, 4, 3, 2, 1, 0]   # surprise
>>
>>The seven is include in both cases, so it's not a true inverse
>>selection either.
> 
> Did you read what Magnus said: "a is the index for the first item to
> include"?  How could r[-3::x] for any x not include the 7?
> 
> Cheers,
> mwh

Yes, and I agreed this is how it works.  The point above was the 7 was 
outside the "in-between" index's. Not that it shouldn't be included. 
And yes, I wasn't looking at it quite correctly as well, but my point is 
still valid in the context it was given.

I originally posted that negative index's were one's based, but then I 
got multiple responses that I was looking at it incorrectly (using the 
wrong model) and I should look at index's as being the places between 
the items. (Or on the left side of the items)  This is also mentioned in 
the tutorial as follows.


from 2.4.1 Docs, Section 3.1.2, Strings:

The best way to remember how slices work is to think of the indices as 
pointing between characters, with the left edge of the first character 
numbered 0. Then the right edge of the last character of a string of n 
characters has index n, for example:

  +---+---+---+---+---+
  | H | e | l | p | A |
  +---+---+---+---+---+
  0   1   2   3   4   5
-5  -4  -3  -2  -1

The first row of numbers gives the position of the indices 0...5 in the 
string; the second row gives the corresponding negative indices. The 
slice from i to j consists of all characters between the edges labeled i 
and j, respectively.
-


But you need a different pair of index's for this to work with negative 
step values as you do with positive step values.  (or switch to right 
side indexing.)

So I tried to find a consistent way for in-between index's to work and 
solution I found "and asked if it might be a possibility" wasn't 
desirable.  (And I was told again I was using the wrong model.) ;-)

So we get back to how it actually works, (base 1 for negative index's), 
Or more precisely .. (len(L)+i) indexing.) which is a little more 
complex visually, but I think is better to teach it correctly from the 
start and avoid the confusions that the in-between index's lead to 
later.  And also avoid the confusion of having two different way of 
looking at it.

Here's the correct way


 From 2.4.1 Docs, section 2.3.6, Sequence Types:
---
s[i] i'th item of s, origin 0 (3)
s[i:j] slice of s from i to j (3), (4)
s[i:j:k] slice of s from i to j with step k (3), (5)

(3)
If i or j is negative, the index is relative to the end of the string: 
len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

(4)
The slice of s from i to j is defined as the sequence of items with 
index k such that i <= k < j. If i or j is greater than len(s), use 
len(s). If i is omitted, use 0. If j is omitted, use len(s). If i is 
greater than or equal to j, the slice is empty.

(5)
The slice of s from i to j with step k is defined as the sequence of 
items with index x = i + n*k such that . In other words, the indices are 
i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never 
including j). If i or j is greater than len(s), use len(s). If i or j 
are omitted then they become ``end'' values (which end depends on the 
sign of k). Note, k cannot be zero.
-


This could be a bit clearer.

Notice this doesn't say to use index's between items. Looking at the 
index's as being either on the left or right creates the 'apparent' 
indexing inconsistency I was referring to.  It looks good at first, but 
breaks down later, so the examples using in-between index's in the docs 
and tutorials should probably be rewritten to show how it actually works 
right from the start.  Something like the following examples with a walk 
through would do.

  ['a', 'b', 'c', 'd', 'e', 'f', 'g']
0123456 <--- i
   -7   -6   -5   -4   -3   -2   -1 <--- len(L)+i

example:  i = -7->len(L) + -7   ->7 + -7 -> 0

L[3] = 3
L[:3] = ['a','b','c']   # L[0:3]
L[3:] = ['d','e','f','g']   # L[3:7]

L[-3] -> 'e'
L[:-3] -> ['a','b','c','d'] # L[-7:-3]
L[-3:] -> ['e','f','g'] # L[-3:len(L)] (use len(L), not 0)

L[-3::-1] -> ['e','d','c','b','a']  # L[-3:-8:-1]
L[:-3:-1] -> ['g','f']  # L[-1:-3:-1]

L[3::-1]  -> ['d','c','b','a']  # L[3:-Len(L)-1:-1](-1 wont' work here)
L[:3:-1]  -> ['g','f','e']  # L[0:3:-1]

L[3:4:1]  i-> ['d']
L[3:2:-1] -> ['d']

L[-4:-3: 1] -> ['e']
L[-4:-5:-1] -> ['e']



(*) The problems stituations are the cases where start and stop are on 
each side of the -1/0 boundary.  This causes diffi

Re: Re: error processing variables

2005-09-09 Thread el chupacabra

>Your problem is that the def statement reassignes the name "toHPU" to a
>function instead of a string.  So when the code runs, you're passing a
>function object to s.copy2.

  So...how do fix it?


>> import shutil
>>
>> #variables
>> s = shutil
>>
>> toHPU = "/etc/sysconfig/network/toHPU.wifi"
>> wlan = "/etc/sysconfig/network/ifcfg-wlan-id-00:0e:38:88:ba:6d"
>> toAnyWifi = "/etc/sysconfig/network/toAny.wifi"
>> wired = "/etc/sysconfig/network/ifcfg-eth-id-00:0b:db:1b:e3:88"
>>
>>
>> def toHPU():
>>
>>
>> s.copy2(toHPU,wlan)
>> s.copy2(toAnyWifi,wired)
>>
>> #end
>>
>> #execute function
>> toHPU()



--=  Posted using GrabIt  =
--=  Binary Usenet downloading made easy =-
-=  Get GrabIt for free from http://www.shemes.com/  =-

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


Re: using % operator to print possibly unitialized data attributes

2005-09-09 Thread François Pinard
[Adam Monsen]

> The following code uses the % operator to print possibly unitialized
> data attributes:
> 8<
> class J:
> name = ''
> value = ''
> def __str__(self):
> vals = self.__class__.__dict__
> vals.update(self.__dict__)
> return 'name="%(name)s" value="%(value)s' % vals

> j = J()
> j.name = "j object"
> print j
> >8

> A couple of questions:
> * is there a simpler or more elegant way to do this?
> * how can I get this to work for new-style classes?

One solution which I used a few times, and which also opens the way to
many other niceties, is to manage so `vals' is a `dict'-like type of
your own.  Then, you write its `__getitem__' method the way you want.

If I remember well, one of the niceties is that whenever `%(EXPR)s'
is used in a format string, EXPR may be a string (well balanced with
regard to parentheses) which you may then choose to "evaluate", for any
definition of "evaluate" which is fruitful for your application. :-)

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where is sys.path initialized?

2005-09-09 Thread Robert Kern
Alex wrote:
> No one is answering this question. Why, is it a bit unclear or what?

Have patience. No one's getting paid to answer your questions.

http://docs.python.org/tut/node8.html#SECTION00811

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: py2app and Bittornado

2005-09-09 Thread kooto (sent by Nabble.com)


bsharitt wrote:
You wouldn't happen to know a nice way to interact with the
PythonMac-SIG group without subscribing and subjecting my inbox to rape
by a bunch of useless messages would you?


Check out Nabble - for python-list@python.org - there is a searchable bi-directional archive/forum http://www.nabble.com/Python---python-list-f2962.html

there is also a forum/archive where you can cross browse and search all Python lists - http://www.nabble.com/Python-f2926.html

for PythonMac-SIG - it's http://www.nabble.com/Python---pythonmac-sig-f2970.html Note all posting are bidirectional, that means the mirror on Nabble will be in synch with Python lists. People who prefer a web forum view can browse and post through the web and discuss things with the list users seamlessly.

hope this helps.

Sent from the Python - python-list forum at Nabble.com.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: where is sys.path initialized?

2005-09-09 Thread Alex
No one is answering this question. Why, is it a bit unclear or what?
All I wanted to do was to add the path C:\Python24\mypython to the
sys.path so that I could put all my stuff there instead of mixing it
with the stuff that comes with the installation. And I wanted to do it
permanently som that I wouldn't have to use sys.path.append every time
I started Python interpreter.

Here is what I did, and it worked, but I still don't know why. If
somebody has an explanation please tell me.

1. My computer -> Properties->Advanced->Environment variables->System
variables ->New

2. In Variable name field enter PYTHONPATH and in Variable value field
enter C:\Python24\mypython

3. OK, OK, OK to close all the dialog boxes.

4. Restart the computer (it's essential to restart the computer and not
just the Python shell).

5. Open the Python shell and enter
>>> import sys
>>> sys.path
If you've done exactly as I've described here you should see
C:\Python24\mypython in the list.

Alex

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


Re: List of integers & L.I.S. (SPOILER)

2005-09-09 Thread Bryan Olson
n00m wrote:
 > It also timed out:(

Could be. Yet you did write:

   > It's incredibly fast!


I never intended to submit this program for competition. The
contest ranks in speed order, and there is no way Python can
compete with truly-compiled languages on such low-level code.
I'd bet money that the algorithm I used (coded in C) can run
with the winners. I also think I'd wager that the Python version
outright trumps them on code size.


My first version bombed for the zero-length sequence. That was a
mistake, sorry, but it may not be one of their test-cases. I
wonder how many of the accepted entries would perform properly.


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


Re: OpenSource documentation problems

2005-09-09 Thread Mike Meyer
Florian Diesch <[EMAIL PROTECTED]> writes:
> A.M. Kuchling <[EMAIL PROTECTED]> wrote:
> Another problem with Wikis is that you have to be online to use them and
> can't use your favourite editor to write.

You need a better browser. Mine - at least on Unix - have an option to
dump textareas into text files, invoke my favorite editor on them, and
then read the file back in when the editor exits. Assuming i'm not
running the browser in that editor in the first place.

If you're using a mozilla derivate, there are a couple of extensions
to give you this functionality. MozEx appears to be DOA, but may work
for you anyway. viewsourcewith works in a recent version of FireFox,
though. TextAreaTools looks promising, but it's more an editor in and
of itself than a way to ship text out to your favorite editor.

> At least for me email is the best medium to report bugs.

Which leaves me using the same editor as my browser does...

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error processing variables

2005-09-09 Thread infidel
> import shutil
>
> #variables
> s = shutil
>
> toHPU = "/etc/sysconfig/network/toHPU.wifi"
> wlan = "/etc/sysconfig/network/ifcfg-wlan-id-00:0e:38:88:ba:6d"
> toAnyWifi = "/etc/sysconfig/network/toAny.wifi"
> wired = "/etc/sysconfig/network/ifcfg-eth-id-00:0b:db:1b:e3:88"
>
>
> def toHPU():
>
>
> s.copy2(toHPU,wlan)
> s.copy2(toAnyWifi,wired)
>
> #end
>
> #execute function
> toHPU()

Your problem is that the def statement reassignes the name "toHPU" to a
function instead of a string.  So when the code runs, you're passing a
function object to s.copy2.

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


Re: python object model diagram

2005-09-09 Thread Peter Hansen
Ara.T.Howard wrote:
> 
> anyone out there know where i might find a python object model diagram?

Python is a programming language; they don't have object model diagrams.

Or maybe you're referring to the Python *source* code?  That's in C, 
which isn't object oriented and wouldn't have an object model diagram 
either.

What is it you really want?

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


Re: simple problem with os.rename() parameters - path with spaces

2005-09-09 Thread Peter Hansen
Tom wrote:
> I'm having a problem using a path with spaces as a parameter to 
> os.rename() in a program on WinXP.
> 
> This works fine at the command line (where the folder "c:\aa bb" exists)
> 
>  > os.rename( "c\aa bb", "c:\cc dd" );
>  >
> 
> But, I can't get it to work in my program, eg.
> 
> print SrcDir
> print NewDir
> os.rename( SrcDir, NewDir );
> 
> when I run this I get something like this:
> 
> "e:\\music\\Joni Mitchell\\ogg-8"
> "e:\\music.ogg\\Joni Mitchell\\ogg-8"

What kind of device is drive E: ?  Are you certain it allows spaces in 
filenames?  Can you do the same renaming *using the same drive* at the 
command line or from Explorer?

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


Re: Question about consistency in python language

2005-09-09 Thread Kay Schluehr
Terry Reedy wrote:
> "Kay Schluehr" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > On the other hand there exists no sorted() method for tuples or lists
> > like join() for strings but it is implemented as a function in Python24
> > that returns a new sorted container. I consider this as an
> > inconsistency across builtin types.
>
> The sorted function is not a list method because it is not only a list
> function or even only a tuple and list function or even only a string,
> tuple, list, array, or dict function.  Its input is **any** iterable.  The
> only way to have it both be general and a method would be to have an
> iterable type and to require that all iterables inherit from that type to
> reap the benefit of being an iterable.  All the itertools functions are
> also functions and not methods of a hypothetical iterable type.  'Iterable'
> is a duck type and hence functions thereof must be functions and not
> methods.
>
> Terry J. Reedy

So what? Then an iterable class providing the __iter__ method may be
factored out as Mike reasonably suggested ( I was wrong with my remark
about duck-typing. The __iter__ method may be the interface I claimed
not being aware of ). Or a sortable trait gets used as I would slightly
prefer - but it's not necassary. To be honest I'm not sure what all the
BDFLs Javaesque interfaces and optional static typing blabla for Py3K
should matter if it's not even possible to create obvious inheritance
hierarchies in favour for accidental generic functions?

Kay

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


Re: Yielding a chain of values

2005-09-09 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>>>unless you are going many levels deep
> (and that's usually a design smell of some kind)
>
> No, its not a bug. its a feature! See the discussion in the recursive
> generator thread below:
http://groups.google.com/group/comp.lang.python/browse_frm/thread/4c749ec4fc5447fb/36f2b915eba66eac?q=recursive+generator&rnum=1#36f2b915eba66eac
>
> In my opinion, traversing recursive data structure is where generator
> shine best. Alternative implementation using iterator is lot more
> difficult and lot less elegant. Unfortunate the right now recursive
> generator would carry a price tag of O(n^2) to the level of depth.

The problem with asymptotic 'big O' notation is that is leaves out both the 
constant multiplier and lesser terms and promotes the misperception that 
'lower order' asymtotic behavior is always preferable.  But much real 
computation is done with small and effectively non-asymptotic values where 
the omitted components *are* significant.

In this case, the O(depth^2) cost applies, I believe, to resumptions (and 
yields) of suspended generators, which are *much* faster than function 
calls, so that the omitted multiplier is relatively small.  Given that 
there is also at least one function call cost for each tree node, I expect 
one would need a somewhat deep (intentionally vague without specific timing 
data) and unbalanced tree for the resume price to be worrisome.

In any case, having an easily written and understood version can help in 
testing a faster and more complicated version, especially on random, 
non-corner case examples.

Terry J. Reedy



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


Re: "grep" database

2005-09-09 Thread Mike Meyer
"Hilbert" <[EMAIL PROTECTED]> writes:
> I've heard of a software on linux that creates a recursive database of
> text files  and then provides an interface for grep-like queries. I'd
> like to use it to find procedures/variables in a large code base.
>
> Any suggestions appreciated.

The great granddaddy of them all is WAIS, but it uses a client-server
model instead of grep-like queries. It has since been standardized as
z39.50. The one most like what you want is probably glimpse, which
includes a command-line tool called "agrep" for searching the
database. Swish and HARVEST also come to mind as tools in that model.

You're most likely to find these tools being used as or bundled as
part of web site search engines. They all support "structured" text
files, meaning they parse them to assign tags to parts of the content,
and let you use those tags 

How big is your data set? I gave up trying to find one that would
properly index 2+ gig of text files - the index data structures kept
running into some form of memory limit. I finally gave up and used
the file system layout to handle part of the search, doing finds on
re's for the name - and a custom tool to look for further structure
inside the files.

If you're going to be dealing with large data sets, I'd like to know
if you find something that works well for you.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


python object model diagram

2005-09-09 Thread Ara.T.Howard

anyone out there know where i might find a python object model diagram?

cheers.

-a
-- 
===
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| Your life dwells amoung the causes of death
| Like a lamp standing in a strong breeze.  --Nagarjuna
===

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


Re: Question about consistency in python language

2005-09-09 Thread Kay Schluehr
Mike Meyer wrote:

> Yes, but the function "sorted" is more useful than a list method
> "sorted" in a duck typing language.

I don't see what this has to do with "duck typing"? sorted() is simply
a generic function accepting different types. I'm not aware that
sorted() requires a specific interface of those types it accepts.

>
> The function sorted works on all iterators. I can do:
>
> >>> def t(n):
> >>>   for i in range(n):
> >>> yield i
> >>> ...
> >>> print sorted(t(5))
>
> and have it work.
>
> If sorted were a method of a class - the it'd have to be implemented
> again for every class iterable class. Either that, or you'd have to
> create an abstract parent of all iterable classes to add it to - which
> seems more appropriate for a B&D language than Python.

Instead of extending a class hierarchy it might even be possible to
hook a trait into the class by means of a __traits__ attribute.

http://fsl.cs.uiuc.edu/~mhills/presentations/TraitsPresentation.pdf

Generators as well as lists and tuples would provide a sortable trait.
The sorted() function could remain available for convenience.

> And even if you do add the abstract class, how do you make my example
> work without explictly converting the iterator to a list type?

I don't know how sorted() is implemented? A naive implementation would
in fact be nothing else then:

def sorted(iter):
l = list(iter)
l.sort()
return l

Kay

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


error processing variables

2005-09-09 Thread Unknown
PROBLEM: for some reason, the variables won't work outside the function.
I tried fix it by converting the variables to str and unicode and still no
joy.
 The only way it works is by typing each source and
 destination file by hand on the shutil.copy2() method.
 Or by specifying the functions *inside* the function itself.

Any ideas?

ERROR:
Traceback (most recent call last):
  File "data/scripts/wifi.py", line 76, in main
toHPU()
  File "data/scripts/wifi.py", line 32, in toHPU
s.copy2(toHPU,wlan)
  File "/usr/lib/python2.4/shutil.py", line 92, in copy2
copyfile(src, dst)
  File "/usr/lib/python2.4/shutil.py", line 41, in copyfile
if _samefile(src, dst):
  File "/usr/lib/python2.4/shutil.py", line 31, in _samefile
return os.path.samefile(src, dst)
  File "/usr/lib/python2.4/posixpath.py", line 218, in samefile
s1 = os.stat(f1)
TypeError: coercing to Unicode: need string or buffer, function found


CODE:

import shutil

#variables
s = shutil

toHPU = "/etc/sysconfig/network/toHPU.wifi"
wlan = "/etc/sysconfig/network/ifcfg-wlan-id-00:0e:38:88:ba:6d"
toAnyWifi = "/etc/sysconfig/network/toAny.wifi"
wired = "/etc/sysconfig/network/ifcfg-eth-id-00:0b:db:1b:e3:88"  


def toHPU():


s.copy2(toHPU,wlan) 
s.copy2(toAnyWifi,wired)
 
#end

#execute function
toHPU()

---


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


Re: Question about consistency in python language

2005-09-09 Thread Terry Reedy

"Kay Schluehr" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On the other hand there exists no sorted() method for tuples or lists
> like join() for strings but it is implemented as a function in Python24
> that returns a new sorted container. I consider this as an
> inconsistency across builtin types.

The sorted function is not a list method because it is not only a list 
function or even only a tuple and list function or even only a string, 
tuple, list, array, or dict function.  Its input is **any** iterable.  The 
only way to have it both be general and a method would be to have an 
iterable type and to require that all iterables inherit from that type to 
reap the benefit of being an iterable.  All the itertools functions are 
also functions and not methods of a hypothetical iterable type.  'Iterable' 
is a duck type and hence functions thereof must be functions and not 
methods.

Terry J. Reedy



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


Re: encryption with python

2005-09-09 Thread Mike Meyer
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> On Wed, 07 Sep 2005 14:31:03 -0700, jlocc wrote:
>> Basically I will like to combine a social security number (9 digits)
>> and a birth date (8 digits, could be padded to be 9) and obtain a new
>> 'student number'. It would be better if the original numbers can't be
>> traced back, they will be kept in a database anyways. Hope this is a
>> bit more specific, thanks!!!
> last_number_used = 123  # or some other appropriate value
>
> def make_studentID():
> global last_number_used
> last_number_used = last_number_used + 1
> return last_number_used
>
> For a real application, I'd check the database to see if the number has
> already been used before returning the number. Also, if you need more
> than four digits in your IDs, I'd add a checksum to the end so you can
> detect many typos and avoid much embarrassment.
[...]
> In a real application you would need to store the global variables in a
> database, otherwise each time you reload the Python script you start
> generating the same IDs over and over again.

For real applications (ignoring your theoretical need to generate the
numbers in a random order) I'd not only store the number in the
database - I'd let the databae generate it. Most have some form of
counter that does exactly what you want without needing to keep track
of it and check the database for consistency.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "grep" database

2005-09-09 Thread Hilbert
thanks!

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


Re: disabling TCP connections, just for one script

2005-09-09 Thread Adam Monsen
Another solution is using a deliberately misconfigured proxy:

import socket
socket.setdefaulttimeout(1)
import urllib
proxies = {'http': 'http://www.example.com:3128'}
url = 'http://www.google.com/'
opener = urllib.FancyURLopener(proxies)
f = opener.open(url)
print f.read()


>From this code I get the following exception:
"IOError: [Errno socket error] timed out"

...and that fits my needs nicely.

-- 
Adam Monsen
http://adammonsen.com/

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


Re: Python linear algebra module -- requesting comments on interface

2005-09-09 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> The module will be public domain.

Various lawyers have suggested that either you cannot do that (is US) or 
that you should not do that.  (You know the joke -- ask two lawyers and you 
get three opinions -- but all depends on your country of residence.)

A license lets you say "I wrote this, you cannot claim that you did" and 
"If you use this, you agree not to sue me".  PD apparently allow both theft 
and (legal) assault.  Somewhere on the python site is a reference to the 
'Academic License' which I believe says about this much (as does the Python 
license) and which is compatible with possible donation to PSF.

Terry J. Reedy




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


Re: How to upgrade to 2.4.1 on Mac OS X tiger

2005-09-09 Thread Trent Mick
[Mike Meyer wrote]
> stri ker <[EMAIL PROTECTED]> writes:
> > Has anyone here upgraded from 2.3 to 2.4 on Tiger?
> > If so how'd ya do it?
> 
> You don't. You install 2.4 in parallel with 2.3. You can do pretty
> much whatever you want with /usr/bin/python, /usr/local/bin/python,
> etc. - Tiger doesn't seem to use those. I don't remember if I replaced
> one or not, but don't touch anything else about the 2.3 installtion.
> 
> I installed the darwinports version of 2.4, and have been using it
> ever since for all my stuff.

There are also the following install options:

- ActivePython:
  http://www.activestate.com/Products/ActivePython/
  (disclaimer: I make this distro)

- MacPython:
  http://undefined.org/python/#python
  by Bob Ippolito

- fink (similar in spirit to the darwinports project) also has a Python
  I believe


Trent

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to upgrade to 2.4.1 on Mac OS X tiger

2005-09-09 Thread Mike Meyer
stri ker <[EMAIL PROTECTED]> writes:
> Has anyone here upgraded from 2.3 to 2.4 on Tiger?
> If so how'd ya do it?

You don't. You install 2.4 in parallel with 2.3. You can do pretty
much whatever you want with /usr/bin/python, /usr/local/bin/python,
etc. - Tiger doesn't seem to use those. I don't remember if I replaced
one or not, but don't touch anything else about the 2.3 installtion.

I installed the darwinports version of 2.4, and have been using it
ever since for all my stuff.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get the return value of a thread?

2005-09-09 Thread Benjamin Niemann
Leo Jay wrote:

> Dear all,
> 
> i would like to get the return value of all threads
> 
> e.g.
> def foo(num):
> if num>10:
> return 1
> elif num>50:
> return 2
> else
> return 0
> 
> 
> after i invoked
> t = thread.start_new_thread(foo,(12,))
> how to get the return value of `foo'?

Take a look at the Queue module. Create a queue instance at let the 'foo
thread' put() its result into it:

fooResult = Queue.Queue()

def foo(num):
result = 0

if num>10:
result = 1
elif num>50:
result = 2

fooResult.put(result)

t = thread.start_new_thread(foo,(12,))

# do other stuff, foo is running in background

r = fooResult.get() # guaranteed to block until result is available
print r

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: disabling TCP connections, just for one script

2005-09-09 Thread Adam Monsen
Nice!!

Since that works, this also works (any socket operations appear to
raise an IOError):

import socket
socket.setdefaulttimeout(0)

Thanks!
-Adam

-- 
Adam Monsen
http://adammonsen.com/

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


Re: Question about consistency in python language

2005-09-09 Thread Mike Meyer
"Kay Schluehr" <[EMAIL PROTECTED]> writes:
> If you define
>
 sep = ""
 sep.join(["d","o","g"])
> "dog"
 sep
> ''
>
> sep is preserved and a new "dog" string is generated. Since sep is
> immutable there is no way to manipulate it inplace.
>
> On the other hand there exists no sorted() method for tuples or lists
> like join() for strings but it is implemented as a function in Python24
> that returns a new sorted container. I consider this as an
> inconsistency across builtin types. Consistent would be following usage
> pattern:
>
 l = [1,3,2]
 l.sorted()
> [1,2,3] # new sorted list
 l.sort()# sort list inplace
 l.appended(4)   # new extended list
> [1,2,3,4]
 l.append(4) # appends an element to the same list
 l
> [1,2,3,4]


Yes, but the function "sorted" is more useful than a list method
"sorted" in a duck typing language.

The function sorted works on all iterators. I can do:

>>> def t(n):
>>>   for i in range(n):
>>> yield i
>>> ...
>>> print sorted(t(5))

and have it work.

If sorted were a method of a class - the it'd have to be implemented
again for every class iterable class. Either that, or you'd have to
create an abstract parent of all iterable classes to add it to - which
seems more appropriate for a B&D language than Python.

And even if you do add the abstract class, how do you make my example
work without explictly converting the iterator to a list type?

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using % operator to print possibly unitialized data attributes

2005-09-09 Thread Adam Monsen
Leif K-Brooks wrote:
> This will update the class's attributes with instance attributes
> when str() is called, which probably isn't what you want.
[...]

Yikes, you're right! Well, I figured out a modification to my original
__str__ code that works for old and new-style classes which doesn't
overwrite the __class__.__dict__:

class J(object):
name = ''
value = ''
def __str__(self):
vals = dict(self.__class__.__dict__)
vals.update(self.__dict__)
return 'name="%(name)s" value="%(value)s' % vals


> What's wrong with the obvious version:
[...]

Oh, that looks nice and clean. I like it.

I also found a recipe in the Python cookbook that works great for
"dumping" objects:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/137951
(shortened: http://snipurl.com/hka7 )

Thanks!
-Adam

-- 
Adam Monsen
http://adammonsen.com/

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


Re: Question about consistency in python language

2005-09-09 Thread Mike Meyer
Dave Benjamin <[EMAIL PROTECTED]> writes:
> Mike Meyer wrote:
>> Dave Benjamin <[EMAIL PROTECTED]> writes:
>>>Python is actually quite consistent in this regard: methods that
>>>modify an object in-place return None;
>> Um, no. list.pop comes to mind as an immediate counterexample. It may
>> be the only one...
> I've never had to look up the return type of "pop" though. The only
> thing even remotely ambigious about that term (at least, if you've
> learned what a stack is) is whether it mutates the object, but I don't
> think I've ever seen a "pop" that didn't (aside from toy examples in
> formal methods / ADT related classes).

Eiffel STACK class has a pop that dosn't return a value - at least in
SmartEiffel. On the other hand, Eiffel makes a *big* deal about the
difference between command features - which change the state - and
query features - which report on the state. That distinction even
shows up in the threading model for Eiffel.

> "os.system" might be a better example, since the return value could be
> one of two obvious things: the status code, or the program's output.

To me, os.system obviously returns the status code. Then again, I know
it's just the unix system() routine, which I've know *much* longer
than there's been a Python.

The point is that what's "obvious" depends on where you're coming
from. If your background is as a Unix developer, the result of
os.system is obvious. If your background is Eiffel or some other
strong ADT area, that pop has a result at all may surprise you.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using % operator to print possibly unitialized data attributes

2005-09-09 Thread Leif K-Brooks
Adam Monsen wrote:
> class J:
> name = ''
> value = ''
> def __str__(self):
> vals = self.__class__.__dict__
> vals.update(self.__dict__)
> return 'name="%(name)s" value="%(value)s' % vals

This will update the class's attributes with instance attributes when
str() is called, which probably isn't what you want. For instance:

 >>> foo = J()
 >>> foo.name = "Joe Bloggs"
 >>> print foo
 name="Joe Bloggs" value="
 >>> bar = J()
 >>> print bar
 name="Joe Bloggs" value="

What's wrong with the obvious version:

class J(object):
name = ''
value = ''
def __str__(self):
return 'name=%r value=%r' % (self.name, self.value)
-- 
http://mail.python.org/mailman/listinfo/python-list


Expected Value

2005-09-09 Thread George
I have never done any programming with python in my life so I will most
definetly need help understanding how I can accomplish this part of my
program.

The function expectP(z) computes E(X) for the random variable
representing a sample over the probability generated by "pf" for the
set of discrete items [1,10]. The constant c is needed so that the
probability sum to 1.0, as required by the definition of probability.
The function pf(r,c,x) returns the probability that item x will be
equal to a randomly chosen variable, denoted by P(x) or P(X=x) in
mathematical texts, where c is the constant mentioned above and r is
needed because we are considering a power law distribution. I need help
in writing the expectP function and do I compile and execute this code
on a linux box.

"""
Module to compute expected value.

>>> showExpectP(0.5)
33410
>>> showExpectP(0.85)
15578
>>> showExpectP(0.9)
12953
>>> showExpectP(0.99)
8693
>>> showExpectP(0.999)
8312

"""

def norm(r):
  "calculate normalization factor for a given exponent"
  # the function for this distribution is  P(x) = c*(x**-r)
  # and the job of this norm function is to calculate c based
  # on the range [1,10**5]
  sum = 0.0
  for i in range(1,1+10**5):
 # final sum would be more accurate by summing from small values
 # to large ones, but this is just a homework, so sum 1,2,..10**5
 sum += float(i)**-r
  return 1.0/sum

def pf(r,c,x):
  "return a power-law probability for a given value"
  # the function for this distribution is  P(x) = c*(x**-r)
  # where the constant c is such that it normalizes the distribution
  return c*(float(x)**-r)

#- between these lines, define expectP() function
-


#- end of expectP() definition


def showExpectP(limit):
  "display ExpectP(limit) by rounding down to nearest integer"
  k = expectP(limit)
  return int(k)

if __name__ == '__main__':
  import doctest, sys
  doctest.testmod(sys.modules[__name__]) 

thankyou sooo much.

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


Re: What's the difference between VAR and _VAR_?

2005-09-09 Thread Erik Max Francis
S. D. Rose wrote:

> I can't get the value of the variable (out of the class function) if it has
> two leading underscores.

Sure you can if you want it hard enough; it's just mangled.

 >>> class C: __x = 1
...
 >>> dir(C)
['_C__x', '__doc__', '__module__']
 >>> c = C()
 >>> dir(c)
['_C__x', '__doc__', '__module__']
 >>> c._C__x
1

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   What is now prov'd was once only imagin'd.
   -- William Blake
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: disabling TCP connections, just for one script

2005-09-09 Thread cakebread
How about this:

import timeoutsocket
timeoutsocket.setDefaultSocketTimeout(0)

This will make all sockets in your Python app fail.

https://svn.plone.org/svn/collective/CMFSquidTool/trunk/timeoutsocket.py

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


Re: nested tuples

2005-09-09 Thread Larry Bates
The first question is why do you need tuples?

But this works:

import csv
filename=r'C:\test.txt'
fp=open(filename,'r')
reader=csv.reader(fp)
tlines=tuple([tuple(x) for x in reader])
fp.close()

Larry Bates

Luis P. Mendes wrote:
> Hi,
> 
> I'm trying to solve this problem:
> 
> suppose I'm reading a csv file and want to create a tuple of all those
> rows and values, like ((row1value1, row1value2, row1value3),(row2value1,
> row2value2, row2value3),..., (rowNvalue1, rowNvalue2, rowNvalue3))
> 
> I haven't found the way to do it just using tuples.  How can I do it?
> 
> Nevertheless, I can solve it like this:
> a=[]
> 
> for row in reader:
> ~   elem = (row[0],row[1],row[2])
> ~   a.append(elem)
> 
> which will result in a list of tuples: [(row1value1, row1value2,
> row1value3),(row2value1, row2value2, row2value3),..., (rowNvalue1,
> rowNvalue2, rowNvalue3)]
> 
> Then, I get what I want with tuple(a).
> 
> 
> 
> Luis P. Mendes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping over arrays in numarray/numeric

2005-09-09 Thread Robert Kern
proof wrote:
> a = range(100)
> b = [a] * 3
> 
> b[1] = [k + i for k, i in zip(b[1], b[2])]
> 
> This is rather slow in python and I thought that kind of things should
> be written using numeric or numarray. I tried to read trough manuals
> but it didn't help me. So how is this done using numeric or numarray?

In [1]: from Numeric import *

In [2]: a = arange(100)

In [3]: b = array((a,a,a))

In [4]: b[1] += b[2]

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: nested tuples

2005-09-09 Thread Max Erickson
"Luis P. Mendes" <[EMAIL PROTECTED]> wrote in
> suppose I'm reading a csv file and want to create a tuple of all
> those rows and values, like ((row1value1, row1value2,
> row1value3),(row2value1, row2value2, row2value3),...,
> (rowNvalue1, rowNvalue2, rowNvalue3)) 
> 
> I haven't found the way to do it just using tuples.  How can I do
> it? 
> 
> Nevertheless, I can solve it like this:
> a=[]
> 
> for row in reader:
> ~   elem = (row[0],row[1],row[2])
> ~   a.append(elem)
> 
> which will result in a list of tuples: [(row1value1, row1value2,
> row1value3),(row2value1, row2value2, row2value3),...,
> (rowNvalue1, rowNvalue2, rowNvalue3)]

tuple() will consume a list.

>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple([(1,2),(3,4),(5,6)])
((1, 2), (3, 4), (5, 6))


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


Re: How to upgrade to 2.4.1 on Mac OS X tiger

2005-09-09 Thread Robert Kern
stri ker wrote:
> Has anyone here upgraded from 2.3 to 2.4 on Tiger?
> If so how'd ya do it?

You just run the official installer.

http://python.org/ftp/python/2.4.1/MacPython-OSX-2.4.1-1.dmg

Note that this does *not* replace 2.3 which was installed by Apple.
That's a good thing. Instead, the executables get installed to
/usr/local/bin . If you want

  $ python

to give you 2.4.1, then make sure that /usr/local/bin comes before
/usr/bin in your $PATH.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: Code for generating validation codes (in images)

2005-09-09 Thread jepler
On Sun, Sep 04, 2005 at 11:10:07AM +0200, Giuseppe di Sabato (aka deelan) wrote:
> take a look at the "pycaptcha" package:
> 

The links on the freshmeat.net page don't work for me --- the downloads are
404'd, and the demo doesn't work.

Jeff


pgpkRlXiyKESW.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Redundant code in multiple methods

2005-09-09 Thread Rob Conner
No you don't need to know Zope to help me. The whole reason I'd even
want to do this is because of Zope though. I made a Zope product, and
now want to perfect it.

some simple example code...


class User:

def View(self):
# play with data here
myHtmlDoc = "pretend this is a uper profile"
return myHtmlDoc
index_html = View

def Edit(self):
# play with data here
myHtmlDoc = "editing the user"
return myHtmlDoc


So when visiting "website.com/User" zope will call User.index_html() or
when you visit "website.com/User/View" zope will call User.View() In
all of the testing/learning I've done on Zope I'm pretty sure that last
item (index_html or View) must be a method, but possible it only needs
to have an __doc__ attribute (otherwise Zope will Error)

The problem comes when I want to have code put into every method.
Perhaps a counter I want to increment on every visit to a User page.
I can do this..


def View(self):
incrementCounter()
# play with data here
myHtmlDoc = "pretend this is a uper profile"
return myHtmlDoc
index_html = View

def Edit(self):
incrementCounter()
# play with data here
myHtmlDoc = "editing the user"
return myHtmlDoc


... but in reality in my real code that one counter increment line ends
up being 20 lines long. An al lot of that "counter code" is actaully
setting up variables I'd like to access within the scope of the given
method. So if you follow me so far, I was wondering how I might change
things to only have one place where I have to maintain the "setup my
method" code, which is pretty much a lot of the same code typed over
and over into all of the methods.
(for a more real life example of things) -


def View(self):
REQUEST = self.REQUEST
SESSION = REQUEST.SESSION
dbConnection = self.getDBConnection()
logger = self.getLogger()
trackStatsHere()
# set up some local variables here
# change some global variables here
try:
myHtmlDoc = """make the htmldocument here using all
of the previous variables"""
# play with data here
return myHtmlDoc
except:
raise "handle the error here"
finally:
dbConnection.close()
index_html = View

def Edit(self):
REQUEST = self.REQUEST
SESSION = REQUEST.SESSION
dbConnection = self.getDBConnection()
logger = self.getLogger()
trackStatsHere()
# set up some local variables here
# change some global variables here
try:
myHtmlDoc = """make the htmldocument here using all
of the previous variables"""
# play with data here
return myHtmlDoc
except:
raise "handle the error here"
finally:
dbConnection.close()


I would ideally like to do something such as this this, or something
where I don't have all of that redundant code.


def __allmethods__(self, methodname):
"gets called when all methods are called"
REQUEST = self.REQUEST
SESSION = REQUEST.SESSION
dbConnection = self.getDBConnection()
logger = self.getLogger()
trackStatsHere()
# set up some local variables here
# change some global variables here
try:
methodname(localvariables)
except:
raise "handle the error here"
finally:
dbConnection.close()

def View(self, localvariables):
myHtmlDoc = """make the htmldocument here using all
of the previous variables"""
# play with data here
return myHtmlDoc
index_html = View

def Edit(self):
myHtmlDoc = """make the htmldocument here using all
of the previous variables"""
# play with data here
return myHtmlDoc


__getattr__ almost does the trick but not quite. So any suggestions on
how to streamline my code here and make it slightly more maintainable.

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


Re: List of integers & L.I.S. (SPOILER)

2005-09-09 Thread n00m
PS:
ALL problems in problems.PDF file (weekly updated):

http://spoj.sphere.pl/problems.pdf

The friendliest online contester I've ever seen! JUST A NON-SUCH.

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


Re: circular import problem

2005-09-09 Thread Terry Reedy

"Learning Python" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> An example in the book I didn't understood well
> two modules files recursively import/from each other

There are past postings available in the archives (via Google) at least, 
that lucided discuss circular imports.  There are also some that recommend 
"don't do that" and give alternatives.  I recommend both.

Terry J. Reedy



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


Re: subprocess solved all my problems

2005-09-09 Thread Do Re Mi chel La Si Do
Hi !

Thank you for this interesting message.

@-salutations

Michel Claveau



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


Python Design Principles

2005-09-09 Thread lechequier
In a previous post, I asked about the inconsistency in usage patterns
in operating on mutable and immutable types. Thanks Dave and everyone
else for answering my question so thoughtfully and helping me to
understand the reasoning about why the different usage patterns are not
deemed to be inconsistent.

But I am still puzzled by the argument that has been given for why
methods that operate on mutable types should return None, namely, that
the designers of python didn't want the users to shoot themselves in
the foot by thinking a method simply returned a result and left the
data structure unchanged.

In the context of fundamental design principles, if you asked a random
sample of Python gurus what is more Pythonesque: preventing users from
shooting themselves in the foot or making things easier to accomplish,
my impression is that people would overwhelmingly choose the latter.
After all, the fact that Python is not strongly typed and is
interpreted rather than compiled gives plenty of ways for people to
shoot themselves in the foot but what is gained is the abilitity to do
more with less code.

But in this instance, by not allowing operations on mutable types to
return the mutated objects, it seems that the other side is being
taken, sacrificing programmer producitivity for concerns about
producing possible side effects. It is somewhat ironic, I think, that
Java, a language whose design principles clearly side on preventing
users from shooting themselves in the foot, much more so thatn Python,
generally allows you to get back the mutated object.

I'm not trying to change minds here but just to understand better how
this particular design decision fits into Python's overall design
principles.

thanks,
Scott

Dave Benjamin wrote:
> [EMAIL PROTECTED] wrote:
> > Let's say I define a list of pairs as follows:
> >
> >>>l = [('d', 3), ('a', 2), ('b', 1)]
> >
> >
> > Can anyone explain why this does not work?
> >
> >>>h = {}.update(l)
> >
> >
> > and instead I have to go:
> >
> >>>h = {}
> >>>h.update(l)
> >
> > to initialize a dictionary with the given list of pairs?
> >
> > when an analagous operation on strings works fine:
> >
> >>>s = "".join(["d","o","g"])
> >
> >
> > Seems inconsistent.
>
> Python is actually quite consistent in this regard: methods that modify
> an object in-place return None; methods that do not modify an object
> in-place return a new object instead. Since strings are immutable, they
> cannot be modified in-place, so it makes sense for the "join" method to
> return a new string. On the other hand, Python's dictionaries are
> imperative-style and so most operations on a dictionary modify an
> existing dictionary.
>
> I was initially bothered by the phenomenon of so many methods returning
> None because they could not be chained. But I have come to deeply
> appreciate this style for a couple of reasons. First, it makes it clear
> which methods are side-effecting (like "update") and which are not (like
> "sort").
>
> Second, it is not always clear what a good return value is for a
> mutator. Perhaps {}.update() should return the dictionary, making
> chaining convenient. Perhaps it should return the total number of items
> after updating. Or maybe it should return the number of new keys that
> were added, or a list of those keys. All of these are plausible
> behaviors; the problem is that "update" is not a function. Its job is to
> change something, not return something. Any possible return value would
> be a convenience for certain tasks and useless for other tasks.
>
> It's also hard to remember, in my opinion. For example, JavaScript has a
> "push" method on the Array object which behaves like Python's "append"
> method on lists:
>
> js> var a = [];
> js> a.push(5);
> 1
> js> a.push(6);
> 2
>
> I bet you that almost nobody knows that "push" returns the new length of
> the Array. It could just as easily have returned "a" here. I could
> always write "a.length", if I really needed to know the new length. This
> sort of thing becomes language trivia, and when I write in JavaScript I
> always ignore the result of "push" because, even if *I* know what it
> returns, chances are that my readers don't.
>
> Another reason that Python adopts the convention of returning None for
> mutators is that it discourages the use of side-effecting code in
> expressions. Mixing side-effects with expressions can lead to code that
> is hard to read and understand. This is often debated by those who know
> better and wish to write things like "h.update(a).update(b)" (method
> chaining) or "while (line = file.readline()): ...". Python's decision is
> pretty clear, and it's also evident in the division between statements
> and expressions.
>
> Regardless of whether you like Python's style decision or not, if you
> dig deeper I think you will find that it is pretty consistent, and that
> there are useful benefits to Python's way of handling side effects.
>
> Dave
>
> PS. If mutators had to return a value, I'd have the

nested tuples

2005-09-09 Thread Luis P. Mendes
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi,

I'm trying to solve this problem:

suppose I'm reading a csv file and want to create a tuple of all those
rows and values, like ((row1value1, row1value2, row1value3),(row2value1,
row2value2, row2value3),..., (rowNvalue1, rowNvalue2, rowNvalue3))

I haven't found the way to do it just using tuples.  How can I do it?

Nevertheless, I can solve it like this:
a=[]

for row in reader:
~   elem = (row[0],row[1],row[2])
~   a.append(elem)

which will result in a list of tuples: [(row1value1, row1value2,
row1value3),(row2value1, row2value2, row2value3),..., (rowNvalue1,
rowNvalue2, rowNvalue3)]

Then, I get what I want with tuple(a).



Luis P. Mendes
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFDIdcvHn4UHCY8rB8RAjBnAJ9hLzbMZVZf3vLZ0iCs2ptK0v6RPwCfRr1S
GHdoy/APTZSWy+rLBA+i0KE=
=vyR6
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List of integers & L.I.S. (SPOILER)

2005-09-09 Thread n00m
It also timed out:(

241056 2005-09-09 20:11:19 ZZZ time limit exceeded  -  7064  PYTH

Btw, have a look at this nicest problem:

http://spoj.sphere.pl/problems/COINS/

My py solution takes #64 place among its best solutions:

http://spoj.sphere.pl/ranks/COINS/start=60

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


Re: Timezone and ISO8601 struggles with datetime and xml.utils.iso8601.parse

2005-09-09 Thread Samuel
> Take a look at the utcoffset method of datetime objects.

This returns 0.
However, meanwhile I figured out a way to do this:

Every datetime object by default does not handle timezones at all, and
as such "isoformat" does not return an offset in the ISO8601 string.
The only way around this appears to be passing the tzinfo to the
constructor every time (datetime.tzinfo is not writeable). I am not
aware of a python-provided implementation for a conrete tzinfo, so I
copied this code:


from datetime import *
import time as _time

STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
DSTOFFSET = STDOFFSET

DSTDIFF = DSTOFFSET - STDOFFSET

class LocalTimezone(tzinfo):
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
else:
return STDOFFSET

def dst(self, dt):
if self._isdst(dt):
return DSTDIFF
else:
return ZERO

def tzname(self, dt):
return _time.tzname[self._isdst(dt)]

def _isdst(self, dt):
tt = (dt.year, dt.month, dt.day,
  dt.hour, dt.minute, dt.second,
  dt.weekday(), 0, -1)
stamp = _time.mktime(tt)
tt = _time.localtime(stamp)
return tt.tm_isdst > 0


from the Python documentation into my program. (I am sure there must be
a better way to do this though.) Then, when passing the
tz.LocalTimezone instance to datetime, isoformat() returns the string
with an offset appended (e.g. +02:00).
The resulting string can then also successfully be parsed with
xml.utils.iso8601.parse().

Thanks for your help!

-Samuel

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


working with multiple frame instances

2005-09-09 Thread fchef
I am looking for some advice on working with Multiple frame instances.
Essentially I need to be able to refer to specific control values in a
frame and be able to hide/show a specific frame. In VB you can
reference a particular frame with something like Controls.Form("My
form").DoSomething. Is there something analogous to this in Python? Or
is there a better approach all together?

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


using % operator to print possibly unitialized data attributes

2005-09-09 Thread Adam Monsen
The following code uses the % operator to print possibly unitialized
data attributes:
8<
class J:
name = ''
value = ''
def __str__(self):
vals = self.__class__.__dict__
vals.update(self.__dict__)
return 'name="%(name)s" value="%(value)s' % vals

j = J()
j.name = "j object"
print j
>8

A couple of questions:
* is there a simpler or more elegant way to do this?
* how can I get this to work for new-style classes?

Thank you,
-Adam

-- 
Adam Monsen <[EMAIL PROTECTED]>
http://adammonsen.com/

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


Re: sys.stdout

2005-09-09 Thread Sébastien Boisgérault

Jorgen Grahn a écrit :

> On 9 Sep 2005 03:40:58 -0700, Sébastien Boisgérault <[EMAIL PROTECTED]> wrote:
> >
> > Fredrik Lundh wrote:
> >> Sébastien Boisgérault wrote:
> >>
> >> > Thanks for your answer. The execution of  your example leads to a
> >> > 'aaa' display during 2 secs, before it is erased by the prompt.
> >> >
> >> > This behavior is standard ? The standard output is not supposed
> >> > to *concatenate* the 'aaa' and the '>>>' ?
> >>
> >> what "python shell" are you using, and what platform are you running
> >> it on?
> >
> > The python interpreter is invoked from a bash/konsole session,
> > inside a KDE env.:
>
> So, it's either of these things:
> - konsole and its bugs/features

Nothing that I could do about it ;)

> - your $TERM settings

My xterm settings ?

> - your readline and its bugs/features

Uh Uh ... I have disabled my $PYTHONSTARTUP script that
was using some features of the readline module, but
without any success ...

> - your ~/.inputrc settings (see the readline man page)

INPUTRC refers to the default Mandrake settings in
etc/inputrc. An old version, 2002. It should be
mostly harmless, right  ...

> It's hard to say what's right and wrong really, and whose fault it is.
> I'm pretty sure it's not Python.  What happens if you try bash?
>
>   tuva:~> bash
>   [EMAIL PROTECTED]:~$ echo -n 'foo'
>   [EMAIL PROTECTED]:~$

Bash (into a konsole, same conditions than befor) seems to be ok:

[EMAIL PROTECTED] boisgera]$ echo -n 'foo'
[EMAIL PROTECTED] boisgera]$

:(

Cheers,

SB

> /Jorgen
>
> --
>   // Jorgen Grahn  \X/algonet.se>   R'lyeh wgah'nagl fhtagn!

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


where is sys.path initialized?

2005-09-09 Thread Alex
Rossum's tutorial states
"Actually, modules are searched in the list of directories given by the
variable sys.path which is initialized from the directory containing
the input script (or the current directory)"

I'm running Python standard installation (ver 2.4) on Windows XP. Where
can I find the "input script" where the sys.path is defined?

Alex

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


Re: disabling TCP connections, just for one script

2005-09-09 Thread Adam Monsen
I know very little about socket programming and even less about
sockey.py... any idea what behavior would have to be modified?

Further complicating matters (for me), it appears some of the socket
programming code is in C, and my C skills are lacking.

-- 
Adam Monsen
http://adammonsen.com/

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


Re: "grep" database

2005-09-09 Thread Adam Monsen
ctags indexes procedures/variables in source code, perhaps it would
help: http://ctags.sf.net/

--
Adam Monsen
http://adammonsen.com/

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


Re: simple problem with os.rename() parameters - path with spaces

2005-09-09 Thread Larry Bates
Are you sure the source directory exists and you
have rights to rename it?  Because the rename works
for me.

But you may want to look at shutil.move and/or
use forward slashes (they work under Windows)

-Larry Bates


Tom wrote:
> I'm having a problem using a path with spaces as a parameter to
> os.rename() in a program on WinXP.
> 
> This works fine at the command line (where the folder "c:\aa bb" exists)
> 
>> os.rename( "c\aa bb", "c:\cc dd" );
>>
> 
> But, I can't get it to work in my program, eg.
> 
> print SrcDir
> print NewDir
> os.rename( SrcDir, NewDir );
> 
> when I run this I get something like this:
> 
> "e:\\music\\Joni Mitchell\\ogg-8"
> "e:\\music.ogg\\Joni Mitchell\\ogg-8"
> 
> Traceback (most recent call last):
>   File "E:\Music\MoveMusic.py", line 64, in ?
> main();
> ...
>   File "E:\Music\MoveMusic.py", line 49, in Visit
> os.mkdir( NewDir );
> OSError: [Errno 22] Invalid argument: '"e:\\music.ogg\\Joni
> Mitchell\\ogg-8"'
> 
> I've tried different combinations of single backslash vs. double
> backslash, and quoted vs. non-quoted, but it always fails.
> 
> The problem is not specific to os.rename.  If I instead use mkdir(
> SrcDir ) I get the same problem.
> 
> Thanks,
> Tom.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


circular import problem

2005-09-09 Thread Learning Python
An example in the book I didn't understood well
two modules files recursively import/from each other

in recur1.py,we have:

x=1
import recur2
y=1


in recur2.py, we have

from recur1 import x
from recur1 import y


If we run interactively at python command line,

>>> import recur1
it has errors like this:
Traceback (most recent call last):
  File "", line 1, in ?
  File "recur1.py", line 2, in ?
import recur2
  File "recur2.py", line 2, in ?
from recur1 import y
ImportError: cannot import name y

I understood this because recur1 is not finished when recur2 is trying
to import y.

However, if you run interactive for recur2.py interactively, it is
fine.
when you run as script from command line, recur1.py is fine. but when
you
python recur2.py at commmand line, it has errors like this:
Traceback (most recent call last):
  File "recur2.py", line 1, in ?
from recur1 import x
  File "recur1.py", line 2, in ?
import recur2
  File "recur2.py", line 2, in ?
from recur1 import y
ImportError: cannot import name y

What's really the problem here?

Thanks

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


Re: Timezone and ISO8601 struggles with datetime and xml.utils.iso8601.parse

2005-09-09 Thread skip

Samuel> mydatetime = datetime.datetime(year, month, day, hour, minute)
Samuel> strtime= mydatetime.isoformat()

Take a look at the utcoffset method of datetime objects.

Samuel> The second problem has to do with the ISO8601 parser, which
Samuel> raises the following error:

Samuel> --
Samuel> Traceback (most recent call last):
Samuel>   File "./timetest.py", line 16, in ?
Samuel> mytimestamp = xml.utils.iso8601.parse(strtime)
Samuel>   File "/usr/lib/python2.4/site-packages/_xmlplus/utils/iso8601.py",
Samuel> line 22, in parse
Samuel> raise ValueError, "unknown or illegal ISO-8601 date format: " + 
`s`
Samuel> ValueError: unknown or illegal ISO-8601 date format:
Samuel> '2005-07-22T10:30:00'
Samuel> --

Samuel> Why does it fail to parse the value returned by the datetime
Samuel> object, and how can I create a parseable time from the datetime
Samuel> object?

One possibility might be that datetime objects stringify with microseconds
included:

>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2005, 9, 9, 12, 52, 38, 677120)
>>> strtime = t.isoformat()
>>> strtime
'2005-09-09T12:52:38.677120'

You can try stripping the microseconds first:

>>> time.strptime(strtime, "%Y-%m-%dT%H:%M:%S")
Traceback (most recent call last):
  File "", line 1, in ?
  File "/Users/skip/local/lib/python2.5/_strptime.py", line 295, in strptime
raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains: .677120
>>> time.strptime(strtime.split(".")[0], "%Y-%m-%dT%H:%M:%S")
(2005, 9, 9, 12, 52, 38, 4, 252, -1)

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


Re: disabling TCP connections, just for one script

2005-09-09 Thread Diez B. Roggisch
Adam Monsen wrote:
> It would be helpful to be able to temporarily disable AF_INET socket
> connections (I don't care about IPv6 for now).

Maybe put an socket.py with mockup funktions in your path before the 
real socket.py. Then you can alter teh behaviour of all necessary functions.

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


"grep" database

2005-09-09 Thread Hilbert
Hello,

I've heard of a software on linux that creates a recursive database of
text files  and then provides an interface for grep-like queries. I'd
like to use it to find procedures/variables in a large code base.

Any suggestions appreciated.

Thanks,
Hilbert

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


Re: Grouping lists

2005-09-09 Thread [EMAIL PROTECTED]
I wasn't sure of what itertools.groupby() is good for. But it serves
your purpose.

>>> lst = [1,1,1,1,3,5,1,1,1,1,7,7,7]
>>>
>>> import itertools
>>> i = 0
>>> groups = []
>>> for k, g in itertools.groupby(lst):
... l = len(list(g))
... if l == 1:
... groups.append(i)
... else:
... groups.append((i, i+l-1))
... i += l
...
>>> groups
[(0, 3), 4, 5, (6, 9), (10, 12)]

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


Re: List of integers & L.I.S. (SPOILER)

2005-09-09 Thread Bryan Olson
n00m wrote:
 > Oh!
 > Seems you misunderstand me!
 > See how the last block in your code should look:
 >
 > for tc in range(10):
 > _ = stdin.readline()
 > sequence = [int(ch) for ch in stdin.readline().split()]
 > supers = supernumbers(sequence)
 > print len(supers)
 > for i in supers:
 >  print i,

Ah, I misunderstood the input. I thought they'd run it once for
each of their test cases. Handling exactly ten inputs sucks, so
how about:

while True:
 if not stdin.readline().strip():
 break
 sequence = [int(ch) for ch in stdin.readline().split()]
 supers = supernumbers(sequence)
 print len(supers)
 for i in supers:
 print i,
 print


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


simple problem with os.rename() parameters - path with spaces

2005-09-09 Thread Tom
I'm having a problem using a path with spaces as a parameter to 
os.rename() in a program on WinXP.

This works fine at the command line (where the folder "c:\aa bb" exists)

 > os.rename( "c\aa bb", "c:\cc dd" );
 >

But, I can't get it to work in my program, eg.

print SrcDir
print NewDir
os.rename( SrcDir, NewDir );

when I run this I get something like this:

"e:\\music\\Joni Mitchell\\ogg-8"
"e:\\music.ogg\\Joni Mitchell\\ogg-8"

Traceback (most recent call last):
   File "E:\Music\MoveMusic.py", line 64, in ?
 main();
...
   File "E:\Music\MoveMusic.py", line 49, in Visit
 os.mkdir( NewDir );
OSError: [Errno 22] Invalid argument: '"e:\\music.ogg\\Joni 
Mitchell\\ogg-8"'

I've tried different combinations of single backslash vs. double 
backslash, and quoted vs. non-quoted, but it always fails.

The problem is not specific to os.rename.  If I instead use mkdir( 
SrcDir ) I get the same problem.

Thanks,
Tom.

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


Re: Grouping lists

2005-09-09 Thread Benji York
PyPK wrote:
> lst = [1,1,1,1,3,5,1,1,1,1,7,7,7]
> I want to group the list so that it returns groups such as
> [(0,3),4,5,(6,9),(10,12)]. which defines the regions which are similar.

You'll probably want to use "groupby" from the itertools module.  See 
http://docs.python.org/lib/itertools-functions.html
--
Benji York

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


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Stefano Masini
On 9/9/05, djw <[EMAIL PROTECTED]> wrote:
> I think, for me, this most important reason is that the stdlib version
> of a module doesn't always completely fill the requirements of the
> project being worked on. That's certainly why I wrote my own, much
> simpler, logging module. In this case, its obvious that the original
> author of the stdlib logging module had different ideas about how
> straightforward and simple a logging module should be. To me, this just
> demonstrates how difficult it is to write good library code - it has to
> try and be everything to everybody without becoming overly general,
> abstract, or bloated.

That's very true. But...
...there are languages (ahem... did I hear somebody say Java? :) that
make it so hard to write code, that one usually prefers using whatever
is already available even if this means adopting a "style" that
doesn't quite match his expectations.
To me, it is not clear which is best: a very comfortable programmer
with a longer todo list, or an unfomfortable programmer with a short
todo list.
So far, I've always struggled to be in the first category, but I'm
amazed when I look back and see how many wheels I reinvented. But
maybe it's just lack of wisdom. :)

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


Re: Python linear algebra module -- requesting comments on interface

2005-09-09 Thread Colin J. Williams
Connelly,

Apologies, my first message was sent in error.

I like your general setup.  You appear to permit matrix operations, 
which the folk at Numeric and, later, numarray did not.

My own package, PyMatrix, has similar aims to yours but it may be slower 
as it is based on numarray.

My package is just about ready for another release but I'm toiling to 
improve the documentation.  I felt that it could be of value to 
newcomers to matrices and so my new documentation is more long-winded 
than yours.  Your overview sets the whole thing out very neatly.

I have made use of Python's properties for transpose, inverse etc.  This 
uses abbreviations and avoids redundant parentheses.

My work was based on the ideas of Huaiyu Zhu, who developed MatPy:
http://matpy.sourceforge.net/

You might be interested in looking at PyMatrix: 
http://www3.sympatico.ca/cjw/PyMatrix/

Best wishes,

Colin W.

C. Barnes wrote:
> Hi, I'm in the process of writing a Python linear
> algebra module.
> 
> The current targeted interface is:
> 
>   http://oregonstate.edu/~barnesc/temp/linalg/
> 
> The interface was originally based on Raymond
> Hettinger's
> Matfunc [1].  However, it has evolved so that now it
> is
> nearly identical to JAMA [2], the Java matrix library.
> 
> I am soliticing comments on this interface.
> 
> Please post up any criticism that you have.  Even
> small
> things -- if something isn't right, it's better to fix
> it now than later.
> 
> I have not made source code available yet, since the
> current code is missing the decompositions and doesn't
> match the new interface.  I'm in the process of
> rewritting the code to match the new interface.  You
> can e-mail me and ask for the old code if you're
> curious
> or skeptical.
> 
> [1]. http://users.rcn.com/python/download/python.htm
> [2]. http://math.nist.gov/javanumerics/jama/
> 
> -
> Brief comparison with Numeric
> -
> 
> Numeric and linalg serve different purposes.
> 
> Numeric is intended to be a general purpose array
> extension.  It takes a "kitchen sink" approach,
> and includes every function which could potentially
> be useful for array manipulations.
> 
> Linalg is intended to handle real/complex vectors
> and matrices, for scientific and 3D applications.
> It has a more restricted scope.  Because it is
> intended for 3D applications, it is optimized
> for dimension 2, 3, 4 operations.
> 
> For the typical matrix operations, the linalg
> interface is much intuitive than Numeric's.  Real
> and imaginary components are always cast to
> doubles, so no headaches are created if a matrix
> is instantiated from a list of integers.  Unlike
> Numeric, the * operator performs matrix
> multiplication, A**-1 computes the matrix inverse,
> A == B returns True or False, and the 2-norm and
> cross product functions exist.
> 
> As previously stated, linalg is optimized for
> matrix arithmetic with small matrices (size 2, 3, 4).
> 
> A (somewhat out of date) set of microbenchmarks [3]
> [4]
> show that linalg is roughly an order of magnitude
> faster than Numeric for dimension 3 vectors and
> matrices.
> 
> [3].
> Microbenchmarks without psyco:
> http://oregonstate.edu/~barnesc/temp/
> numeric_vs_linalg_prelim-2005-09-07.pdf
> 
> [4].
> Microbenchmarks with psyco:
> http://oregonstate.edu/~barnesc/temp/
> numeric_vs_linalg_prelim_psyco-2005-09-07.pdf
> 
> 
> 
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around 
> http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Grouping lists

2005-09-09 Thread PyPK
If I have a list say

lst = [1,1,1,1,3,5,1,1,1,1,7,7,7]
I want to group the list so that it returns groups such as
[(0,3),4,5,(6,9),(10,12)]. which defines the regions which are similar.

Thanks,

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


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Stefano Masini
On 9/9/05, Michael Amrhein <[EMAIL PROTECTED]> wrote:
> Did you take a look at pyPI (http://www.python.org/pypi) ?
> At least you'd find another odict ...

Oh, yeah. And another filesystem abstraction layer... and another xml
serialization methodology... :)
PyPI is actually pretty cool. If I had to vote for something going
into a "testing" stdlib, I'd vote for PyPI.

You see, that's my point, we have too many! :)

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


Re: Yielding a chain of values

2005-09-09 Thread [EMAIL PROTECTED]
>>unless you are going many levels deep
(and that's usually a design smell of some kind)

No, its not a bug. its a feature! See the discussion in the recursive
generator thread below:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/4c749ec4fc5447fb/36f2b915eba66eac?q=recursive+generator&rnum=1#36f2b915eba66eac

In my opinion, traversing recursive data structure is where generator
shine best. Alternative implementation using iterator is lot more
difficult and lot less elegant. Unfortunate the right now recursive
generator would carry a price tag of O(n^2) to the level of depth.

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


Re: Create new instance of Python class in C

2005-09-09 Thread Sybren Stuvel
djw enlightened us with:
> Personally, I would try Psyco first, and consider Pyrex next.

Ok, I'll take a look at those.

> Are you sure your algorithm can't be optimized first, before you
> start trying to write this in C?

I'm sure there will be optimizations, but profiling showed that the
copying of the puzzles took the most time. Since the copy.deepcopy()
function is implemented it Python, I'd thought it would get quite a
speed boost when done in C instead.

As a side-question: how would I go about compiling my C module in
Windows, if I want to ship a Windows version?

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re module help

2005-09-09 Thread Daniel Dittmar
[EMAIL PROTECTED] wrote:
> if I start replacing regex by re I get stuck at replacement of
>regex.symcomp() and regex.pattern()

Groups identified by names are part of the standard regular expression 
syntax:
regex.symcomp ('\([a-z][a-z0-9]*\)')
becomes
re.compile ('(?Pid[a-z][a-z0-9]*)')

I get AttributeError for both regex.pattern and regex.compile 
('abc').pattern.

re compiled regular expression have a pattern attribute, this was named 
givenpat and realpat in the regex module.

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


Re: distutils question

2005-09-09 Thread Fredrik Lundh
Joachim Dahl wrote:

> E.g., say I want to compile a project as:
>
> gcc -Ddef1 -c foo.c -o foo_def1.o
> gcc -Ddef2 -c foo.c -o foo_def2.o
> gcc foo_def1.o foo_def2.o -o myext_module.o
>
> How would I do that using distutils? It doesn't seem to be possible with
> the normal core.setup method, and distutils.ccompiler seems to be the
> best option, but I couldn't get it working...

easy: add a new C file (e.g. myext_module.c) that includes "foo.c"
twice (using define/undef/ifdef), and compile the new file instead.

almost as easy: change foo.c so it includes itself.

 



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


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Dave Brueck
Stefano Masini wrote:
> I wonder how many people (including myself) have implemented their own
> versions of such modules, at least once in their pythonic life. I
> indeed have my own odict (even same name! :). My own pathutils
> (different name, but same stuff). My own validate... and so forth.
> 
> This is just too bad.
> There are a few ares where everybody seems to be implementing their
> own stuff over and over: logging, file handling, ordered dictionaries,
> data serialization, and maybe a few more.
> I don't know what's the ultimate problem, but I think there are 3 main 
> reasons:
> 1) poor communication inside the community (mhm... arguable)
> 2) lack of a rich standard library (I heard this more than once)
> 3) python is such an easy language that the "I'll do it myself" evil
> side lying hidden inside each one of us comes up a little too often,
> and prevents from spending more time on research of what's available.

IMO the reason is something similar to #3 (above and beyond #1 and #2 by a long 
shot). The cost of developing _exactly_ what you need often is (or at least 
*appears* to be) the same as or lower than bending to use what somebody else 
has 
already built.

(my wheel reinvention has typically covered config files, logging, and simple 
HTTP request/response/header processing)

> It seems to me that this tendency is hurting python

I think it helps on the side of innovation - the cost of exploring new ideas is 
cheaper than in many other languages, so in theory the community should be able 
to stumble upon truly great ways of doing things faster than would otherwise be 
possible. The problem lies in knowing when we've found that really good way of 
doing something, and then nudging more and more people to use it and refine it 
without turning it into a bloated one-size-fits-all solution.

I think we have half of what we need - people like Fuzzyman coming up with 
handy 
modules and then making them available for others to use. But right now it's 
hard for a developer to wade through all the available choices out there and 
know which one to pick.

Maybe instead of being included in the standard library, some modules could at 
least attain some "recommended" status by the community. You can't exactly tell 
people to stop working on their pet project because it's not special or 
different enough from some other solution, so maybe the solution is to go the 
other direction and single out some of the really best ones, and hope that the 
really good projects can begin to gain more momentum.

For example, there are several choices available to you if you need to create a 
standalone Windows executable; if it were up to me I'd label py2exe "blessed by 
the BDFL!", ask the other tool builders to justify the existence of their 
alternatives, and then ask them to consider joining forces and working on 
py2exe 
instead. But of course I'm _not_ in charge, I don't even know if the BDFL likes 
py2exe, and it can be really tough knowing which 1 or 2 solutions should 
receive 
recommended status.

FWIW, RubyOnRails vs all the Python web frameworks is exactly what you're 
talking about. What makes ROR great has little to do with technology as far as 
I 
can tell, it's all about lots of people pooling their efforts - some of them 
probably not seeing things develop precisely as they'd prefer, but remaining 
willing to contribute anyway.

Many projects (Python-related or not) often seem to lack precisely what has 
helped Python itself evolve so well - a single person with decision power who 
is 
also trusted enough to make good decisions, such that when disagreements arise 
they don't typically end in the project being forked (the number of times 
people 
disagreed but continued to contribute to Python is far higher than the number 
of 
times they left to form Prothon, Ruby, and so on).

In the end, domain-specific BDFLs and their projects just might have to buble 
to 
the top on their own, so maybe the best thing to do is find the project you 
think is the best and then begin contributing and promoting it.

> and I wonder if
> there is something that could be done about it. I once followed a
> discussion about placing one of the available third party modules for
> file handling inside the standard library. I can't remember its name
> right now, but the discussion quickly became hot with considerations
> about the module not being "right" enough to fit the standard library.

I think an extremely rich standard library is both a blessing and a curse. It's 
so handy to have what you need already there, but as you point out it becomes 
quite a debate to know what should be added. For one, a module to be added 
needs 
to be sufficiently broad in scope and power to be widely useful, but this often 
breeds complexity (e.g. the logging package added in Py2.3 sure looks powerful, 
but other than playing around with it for a few minutes I've never used it in a 
real app because it's a little overwhelming and it see

disabling TCP connections, just for one script

2005-09-09 Thread Adam Monsen
It would be helpful to be able to temporarily disable AF_INET socket
connections (I don't care about IPv6 for now).

What I'd like to do is create an environment for a Python script that
appears like the network interface is down, so any remote socket stuff
should fail (like an HTTP GET request to Google's home page, for
example).

Anyone know an easy way to do that? Maybe by manipulating the socket
module or something? I'd still like to be able to access the internet
from other programs (like my Web browser, IM app, etc.) while I'm
working on this script, so unplugging the network cable or just
temporarily shutting down networking for the whole system aren't really
acceptable solutions.

Maybe chroot would be useful, but this seems a little complicated for
what I'm trying to do. Setting up some kind of Xen or UML (user mode
Linux) environment, and just disabling networking within that virtual
machine would possibly work, too.

--
Adam Monsen
http://adammonsen.com/

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


looping over arrays in numarray/numeric

2005-09-09 Thread proof
a = range(100)
b = [a] * 3

b[1] = [k + i for k, i in zip(b[1], b[2])]

This is rather slow in python and I thought that kind of things should
be written using numeric or numarray. I tried to read trough manuals
but it didn't help me. So how is this done using numeric or numarray?

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


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread djw
Stefano Masini wrote:

> I don't know what's the ultimate problem, but I think there are 3 main 
> reasons:
> 1) poor communication inside the community (mhm... arguable)
> 2) lack of a rich standard library (I heard this more than once)
> 3) python is such an easy language that the "I'll do it myself" evil
> side lying hidden inside each one of us comes up a little too often,
> and prevents from spending more time on research of what's available.
> 

I think, for me, this most important reason is that the stdlib version 
of a module doesn't always completely fill the requirements of the 
project being worked on. That's certainly why I wrote my own, much 
simpler, logging module. In this case, its obvious that the original 
author of the stdlib logging module had different ideas about how 
straightforward and simple a logging module should be. To me, this just 
demonstrates how difficult it is to write good library code - it has to 
try and be everything to everybody without becoming overly general, 
abstract, or bloated.

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


Re: Create new instance of Python class in C

2005-09-09 Thread djw
Sybren Stuvel wrote:
> Hi people,
> 
> I'm creating a program that can solve and create Sudoku puzzles. My
> creation function needs to make a lot of copies of a puzzle. Until
> now, I used copy.deepcopy(), but that's too slow. I want to implement
> such a copying function in C and use that instead. My idea about this
> is:
> 
> - Get the data from a puzzle (a list containing lists containing
>   strings) and make a copy of it. That's coded already.
> 
> - Create a new SodokuPuzzle instance and assign the data to it.
> 
> That last step can be done by passing the data to the constructor, so
> that's easy too once I know how to do that in C. My question is: how
> do I create a new instance in C of a class written in Python? I've
> searched Google, but found nothing of help.
> 
> Sybren
Personally, I would try Psyco first, and consider Pyrex next. Are you 
sure your algorithm can't be optimized first, before you start trying to 
write this in C?

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


Re: Why do Pythoneers reinvent the wheel?

2005-09-09 Thread Michael Amrhein
Stefano Masini schrieb:
> On 8 Sep 2005 08:24:50 -0700, Fuzzyman <[EMAIL PROTECTED]> wrote:
> 
>>What is pythonutils ?
>>=
>>ConfigObj - simple config file handling
>>validate - validation and type conversion system
>>listquote - string to list conversion
>>StandOut - simple logging and output control object
>>pathutils - for working with paths and files
>>cgiutils - cgi helpers
>>urlpath - functions for handling URLs
>>odict - Ordered Dictionary Class
> 
> 
> Fuzzyman, your post reminded me of something I can't stop thinking
> about. Please don't take this as a critique on your work. I place
> myself on the same side of yours.
> I just wanted to share this thought with everybody had an opinion about it.
> 
> I wonder how many people (including myself) have implemented their own
> versions of such modules, at least once in their pythonic life. I
> indeed have my own odict (even same name! :). My own pathutils
> (different name, but same stuff). My own validate... and so forth.
> 
> This is just too bad.
> There are a few ares where everybody seems to be implementing their
> own stuff over and over: logging, file handling, ordered dictionaries,
> data serialization, and maybe a few more.
> I don't know what's the ultimate problem, but I think there are 3 main 
> reasons:
> 1) poor communication inside the community (mhm... arguable)
> 2) lack of a rich standard library (I heard this more than once)
> 3) python is such an easy language that the "I'll do it myself" evil
> side lying hidden inside each one of us comes up a little too often,
> and prevents from spending more time on research of what's available.
> 
> It seems to me that this tendency is hurting python, and I wonder if
> there is something that could be done about it. I once followed a
> discussion about placing one of the available third party modules for
> file handling inside the standard library. I can't remember its name
> right now, but the discussion quickly became hot with considerations
> about the module not being "right" enough to fit the standard library.
> The points were right, but in some sense it's a pity because by being
> in the stdlib it could have had a lot more visibility and maybe people
> would have stopped writing their own, and would have begun using it.
> Then maybe, if it was not perfect, people would have begun improving
> it, and by now we would have a solid feature available to everybody.
> 
> mhm... could it be a good idea to have two versions of the stdlib? One
> stable, and one testing, where stuff could be thrown in without being
> too picky, in order to let the community decide and improve?
> 
> Again, Fuzzyman, your post was just the excuse to get me started. I
> understand and respect your work, also because you put the remarkable
> effort to make it publicly available.
> 
> That's my two cents,
> stefano

Did you take a look at pyPI (http://www.python.org/pypi) ?
At least you'd find another odict ...
;-) Michael
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >