Re: TurboGears /.-ed, >new == True< or >new == "True"

2005-10-13 Thread Erik Max Francis
Andy Leszczynski wrote:

> So how does it correspond to other piece of the code:
> 
> 2 def notfound(self, pagename):
> 3 return dict(pagename=pagename, data="", new=True)
> 
> new is a boolean here?

It comes through as a CGI query.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Men and women, women and men. It will never work.
   -- Erica Jong
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a __filename__ predefined attribute to 2.5?

2005-10-13 Thread Steve Holden
Rune Strand wrote:
> Ok, Alex. I know a good explanation when I see one. Thanks!
> 
Make that "...when someone beats me over the head with it" ;-) Glad you 
have the explanation you needed, anyway.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: installer for amd64 build of python?

2005-10-13 Thread magneticlemur
Brett,

>I don't have an answer for you, but just to clarity for future
>readers... based on the quote above, I assume you mean a native 64-bit
>build for Windows, right?  You never stated what platform you need this
>for, I for one use a 64-bit build of Python on Linux just fine... but
>yes, Windows is another story, especially if you want it built with the
>super-mega-pro VS with optimizations and all that jazz they use for
>official 32-bit Windows binaries.

Yes I carefully checked my message twice and completely
missed the fact that I left out the magic words Windows x64. (d'uh me.)
As you say, for my linux 64 builds, it works perfectly out
of the box. (surprise)

mike

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


Re: Multiple assignments simplification

2005-10-13 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I don't know if C++ compilers can do such optimizations.

working on a Python to C/C++ translator without knowing what kind
of optimizations a C/C++ compiler can do for you sounds like a great
way to waste your time...

(I would be rather bit surprised if any contemporary C or C++ compiler
didn't generate optimal machine code for source code that contains swaps
like the one you posted.  it won't look at just the swap statement, however;
the interesting thing is where the values came from, and what you're doing
with the values later on. minimizing the number of assignment statements in
the swap translation won't change a thing...)

 



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


Re: Setdefault bypasses __setitem__

2005-10-13 Thread Diez B. Roggisch
Ron Garret wrote:
> Is this a bug or a feature?
> 
> class mydict(dict):
>def __setitem__(self, key, val):
>  print 'foo'
>  dict.__setitem__(self, key, val)
> 
> 
d=mydict()
d[1]=2
> 
> foo
> 
d.setdefault(2,3)


Feature. If it wouldn't bypass __setitem__, how exactly would you make a 
default-item? Using __setitem__ implies a key. So if setdefault
was implemented as

def setdefault(self, v):
 self["SOME_DEFAULT_KEY_NAME"] = v

and later on one writes e.g. a HTML-page with a form input field named 
"SOME_DEFAULT_KEY_NAME" that gets stored in a dict - it would overwrite 
the default value.

So it has to bypass __setitem__, as otherwise it can't distinguish 
between "real" and the default value - the latter one is not allowed to 
have a key that is in any imaginable way used by the user.

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


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Diez B. Roggisch
Delaney, Timothy (Tim) wrote:
> Tom Anderson wrote:
> 
> 
>>Except that in smalltalk, this isn't true: in ST, every variable
>>*appears* to contain a reference to an object, but implementations
>>may not actually work like that. In particular, SmallTalk 80 (and
>>some earlier smalltalks, and all subsequent smalltalks, i think)
>>handles small integers (those that fit in wordsize-1 bits)
>>differently: all variables contain a word, whose bottom bit is a tag
>>bit; if it's one, the word is a genuine reference, and if it's zero,
>>the top bits of the word contain a signed integer.
> 
> 
> This type of implementation has been discussed on python-dev. IIRC it
> was decided by Guido that unless anyone wanted to implement it and show
> a significant performance advantage without any regressions on any
> platform, it wasn't worth it.

AFAIK some LISPs do a similar trick to carry int values on cons-cells. 
And by this tehy reduce integer precision to 28 bit or something. Surely 
_not_ going to pass a regression test suite :)

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


Re: Scope problem with nested functions.

2005-10-13 Thread Fredrik Lundh
<[EMAIL PROTECTED]> wrote

> I'm having trouble resolving a scope problem. I have a module,
> called from another script, with this structure:

the code you posted gives a syntax error.  if I fix that, and add some
boilerplate to call getCcyMappings from inside the parseFile function,
I get:

Traceback (most recent call last):
  File "script.py", line 19, in ?
parseFile(0, 0, 0)
  File "script.py", line 17, in parseFile
getCcyMappings()
  File "script.py", line 8, in getCcyMappings
ccyMappings['CAN'] = ['CAD'] # for example.
NameError: global name 'ccyMappings' is not defined

which tells you that there is no *global* variable named ccyMappings.

the ccyMappings variable in your example isn't a global variable; it's local
to the parseFile function, and can be accessed from that function and any
inner functions via normal lexical scoping rules (=access, but not rebind).

however, the global statement tells Python that the given name is a global
variable, and that any attempts to access or rebind that variable should be
done at the global (=module) level.

if you remove the global statement, Python will look for variables using
ordinary lexical scoping, and things will work as expected.

 



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


Re: Looking for a Python mentor

2005-10-13 Thread Rob Cowie
I'll gladly give you a hand. I should point out - I'm no expert. I
think I've reached a point a bit beyond yours; I learnt OO programming
principles with java and have spent this last Summer learning python. I
have a good grasp of it.

If you want to get in touch, email  rob_cowie AT mac DOT com

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


Re: A Tree class, my $0.02 contribution to the python community.

2005-10-13 Thread Antoon Pardon
Op 2005-10-12, George Sakkis schreef <[EMAIL PROTECTED]>:
> "Antoon Pardon" <[EMAIL PROTECTED]> wrote:
>> Comments are welcome:
>>
>>   http://www.pardon-sleeuwaegen.be/antoon/avltree.html
>
> How about adding two shortcut methods, nextkey(k) and prevkey(k), to return 
> the next and previous
> key respectively ? For instance nextkey would be equivalent to (untested):

I'll file this as: I'll probably never need it, so I'm going to resist
the temptation to add them now. If i find out I'm wrong, I can still do
so later.

> def nextkey(self, key):
> iter = self[key:]
> first = iter.next()
> if key not in self: return first
> else: return iter.next()

I think the if statement can be replaced by:

  if not self.cmp(key, first) == 0: return first

> Also for consistency, nextvalue(k), prevvalue(k), nextitem(k), previtem(k) 
> would be reasonable
> additions.
>
> And a question: what does step do if the keys are not integers since you 
> restrict step to be integer
> ?

It skips keys/items/values.

>>> radio = [
...'alfa', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot', 'golf', 
'hotel', 'india',
...'juliet', 'kilo', 'lima', 'mike', 'november', 'oscar', 'papa', 
'quebec', 'romeo',
...'sierra', 'tango', 'uniform', 'victor', 'whiskey', 'x-ray', 
'yankee', 'zulu' ]
>>> 
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> from avltree import Tree
>>> t=Tree(zip(radio,letters))
>>> t.keys('choco',None,3)
['delta', 'golf', 'juliet', 'mike', 'papa', 'sierra', 'victor', 'yankee']
>>> t.values('bureau',None,4)
['c', 'g', 'k', 'o', 's', 'w']


What would you have in mind if step would have been a string here?

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


Re: Perl-Python-a-Day: Sorting

2005-10-13 Thread Diez B. Roggisch
> In Perl, sort is a function, not some Object Oriented thing. It returns
> the sorted result as another list. This is very simple and nice.

And sometimes exteremely stupid - if your list is large, and making a 
copy just form sorting it (when you don't have to keep a referenece to 
the old list) is highly inefficient.

Calling this stupid tells us just a little bit more of your total lack 
of programming fundamentals.

Not to mention that writing a helper function

def sorted(l):
 l = l[:]
 l.sort()
 return l

to have sorted in versions below 2.4 isn't exactly "magic." But hey, 
we're talking about Xah Lee, a guy who believes his hair could have 
saved the world [1]


Diez

[1] http://xahlee.org/PageTwo_dir/Personal_dir/mi_pixra.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jargons of Info Tech industry

2005-10-13 Thread Paul Rubin
Roedy Green <[EMAIL PROTECTED]> writes:
> Next Mr. Phish had to present his passport etc when he got his Thawte
> ID.  Now Interpol has a much better handle on putting him in jail.
> He can't repudiate his phishing attempt.

Any underage drinker in a college town can tell you a hundred ways to
get sufficient fake ID to get around that.

See also: http://www.ahbl.org/funny/response1.php

I'll let others here fill in the blanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Here I am again, same old arguments

2005-10-13 Thread CJ
 
Wow, thanks alot. I pretty much (due to my own desire to get the program to 
)(@#T(=!!! work and 
be done with it) just turned the list into a function that returns a list that 
isn't attached to 
anything but the function itself, but I've taken the advice to heart.

Most of what you posted makes sense, and is in fact easier than what I was 
doing, but I have 
three questions:

1) Why no global variables? I'm taking your word for it that they're bad. Far 
be it from me to 
argue with you, but why are they bad ideas to begin with? Most of the languages 
I've used up to 
this point have been reliant on globals, so I'm not entirely sure why they 
shouldn't be used.

2) Why no for loop with an index? Again, far be it from me to argue, but it 
seemed perfect for 
my program. 

3) Where do I find a command list, with syntax and all that fun stuff for 
Python? I've explored 
the python site to no end, but I can't seem to find a list.


Again, thanks to everyone who put my crappy noob proggie through the blender :D 
I really did 
learn alot. Like how my 60 line program got turned into a 15 line code snippet. 
(I'm not being 
sarcastic, really, thanks)




-
Wait a minute. I can use my PSP to play GAMES?!?





Steven D'Aprano <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> On Sun, 09 Oct 2005 07:02:52 +, CJ wrote:
> 
>>Okay, same program, different issue. Thanks to the help that I was
>> given I was able to complete my program to find variables in a list
>> that were repeated, and display them once, and how many times they
>> appeared in the list. And it worked great! 
>> 
>>But, being the perfectionist that I am, I wanted to make the
>>proggie 
>> allow any size of list, and not have to be recoded every time. So
>> step one was to not make the program reliant on the list itself being
>> of X length all the time.
> 
> First off -- don't use a for loop with an index as you are doing.
>  
>> #setup variables
>> grub=[3,25,3,5,3,"a","a","BOB",3,3,45,36,26,25,"a",3,3,3,"bob","BOB",6
>> 7] grubrpt=grub
>> cntro=0
>> cntrt=0
>> rpt=0
>> skipped=0
> 
> You are doing too much manual work! Let Python do the lion's share of
> the work for you!
>  
>> #set up for variable length of grub
>> ttllen=len(grub)-1
> 
> Why are you subtracting one from the length of the list?
> 
>> print "The heck is this for loop doing?" 
>> for point in range(0,ttllen,1):
> 
> Using point as a loop index is generally a bad idea. The result coming
> from range is not a point, it is an integer, so why call it a point?
> 
> You are also over-specifying the input arguments to range. If the step
> size is one, you don't need to specify it -- that's the default. You
> just make it harder to read, for no reason. Likewise the initial
> starting value of zero. Just use range(ttllen).
> 
> This, by the way, will return a list [0, 1, 2, ... , length of list -
> TWO] because you already subtracted one from the length.
> 
>> print "Here's Grub=",grub
>> print "And grubrpt=",grubrpt
>> grubrpt[point]="blk"
> 
> As others have pointed out, grub and grubrpt are both names for the
> same list. Changing one changes the other.
> 
> 
>> #Makes sure that there are not multiple prints. 
>> def alrdy_dn(grub,grubrpt):
>> if grub[cntro] in grubrpt:
> 
> Ew!!! Global variables!!!
> 
> Bad programmer! No biscuit!!!
> 
> *wink*
> 
> Global variables are almost always a BAD idea.
> 
>> return grubrpt
>> else:
>> print grub[cntro],"appears in list",rpt,"times."
>> grubrpt[grubrpt.index("blk")]=grub[cntro] return grubrpt
> 
> This is a strange function. What exactly is it meant to do? It
> combines user interface (printing the number of times each item
> appears) and functionality (counting the number of times each item
> appears) and side effects (changing the list), before returning one of
> the input arguments again.
> 
> At least two of those things (counting the items, and printing the
> results) should be separated into different functions for ease of
> comprehension.
> 
> I'm going to skip the rest of your code, because I don't understand it
> and am too lazy, er, I mean busy, to spend the time trying to decipher
> it. Especially since the function you are trying to duplicate manually
> is so easy to do if you work with Python instead of against it.
> 
> def count_item(L, item):
> """Count the number of times item appears in list L."""
> return L.count(item)
> 
> Or wait... that's too easy :-)
> 
> If you want to roll your own, then do it like this:
> 
> def count_item(L, item):
> """Count the number of times item appears in list L by reinventing
> the wheel."""
> n = 0
> for obj in L:
> if obj == item:
> n += 1
> return n
> 
> Notice that we don't change the list at any time. Why change it? That
> just adds complexity to our program and adds extra places to make
> bugs. Of which you have many :-)
> 
> Now you use it like this:
> 
> grub=[3,25,3,5,

Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Paul Rubin
"Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
> AFAIK some LISPs do a similar trick to carry int values on
> cons-cells. And by this tehy reduce integer precision to 28 bit or
> something. Surely _not_ going to pass a regression test suite :)

Lisps often use just one tag bit, to distinguish between an immediate
object and a heap object.  With int/long unification, Python shouldn't
be able to tell the difference between an immediate int and a heap int.

I seem to remember that KCL (and maybe GCL/AKCL) uses heap-consed ints
just like Python does.  It doesn't seem to be disastrous.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installer for amd64 build of python?

2005-10-13 Thread Martin v. Löwis
[EMAIL PROTECTED] wrote:
> Does anyone know of an available downloader for an amd64 bit
> build of (a modern) python?

There is no official build. The only official Win64 build is
for Itanium, see www.python.org/2.4.2

> I've done my due diligence search of python docs and
> mailing archives, and I'm somewhat mystified by the lack of info
> on this topic.

I'm not at all mystified. The operating system was only released
after the release of Python 2.4, there is no official compiler
available yet to the general public, and I don't have the hardware
to test such a release.

It's fairly likely that Python 2.5 will not see official AMD64
Windows binaries, either.

> I'm embedding python in a native 64 bit
> application so python32 using WOW64
> is not an option for me.

So you should build this on your own.

> Alternatively, does anyone have experience
> of using the visual studio files in the PCBuild
> directory under amd64?

A number of people have tried this. There is one open issue
with signal handling: VS 2005 will apparently drop compatibility
with Standard C in one aspect where previous releases used to
be C compatible (namely, processing of unsupported signal
numbers in signal(3)). Because of that, Python will raise
an assertion failure in the debug build.

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


Re: Setdefault bypasses __setitem__

2005-10-13 Thread Peter Otten
Diez B. Roggisch wrote:

> Ron Garret wrote:
>> Is this a bug or a feature?
>> 
>> class mydict(dict):
>>def __setitem__(self, key, val):
>>  print 'foo'
>>  dict.__setitem__(self, key, val)
>> 
>> 
>d=mydict()
>d[1]=2
>> 
>> foo
>> 
>d.setdefault(2,3)
> 
> 
> Feature. If it wouldn't bypass __setitem__, how exactly would you make a
> default-item? Using __setitem__ implies a key. So if setdefault
> was implemented as
> 
> def setdefault(self, v):
>  self["SOME_DEFAULT_KEY_NAME"] = v
> 
> and later on one writes e.g. a HTML-page with a form input field named
> "SOME_DEFAULT_KEY_NAME" that gets stored in a dict - it would overwrite
> the default value.
> 
> So it has to bypass __setitem__, as otherwise it can't distinguish
> between "real" and the default value - the latter one is not allowed to
> have a key that is in any imaginable way used by the user.

The implementation is certainly a design decision. setdefault() could be
implemented in terms of __set/getitem__() as

def setdefault(self, key, value=None):
try:
return self[key]
except KeyError:
self[key] = value
return self[key]

I guess it's not done for performance reasons. 

Peter

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


Re: installer for amd64 build of python?

2005-10-13 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> Does anyone know of an available downloader for an amd64 bit
> build of (a modern) python?

I've gotten a bug report from someone using Python under Linux on an
amd64, so compiling for 64 bits definitely is feasible.  You could try
the Fedora Core 4 amd64 distro (http://fedora.redhat.com).

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


Re: Jargons of Info Tech industry

2005-10-13 Thread Ross Bamford
On Thu, 13 Oct 2005 09:04:17 +0100, > wrote:

> Roedy Green <[EMAIL PROTECTED]> writes:
>> Next Mr. Phish had to present his passport etc when he got his Thawte
>> ID.  Now Interpol has a much better handle on putting him in jail.
>> He can't repudiate his phishing attempt.
>
> Any underage drinker in a college town can tell you a hundred ways to
> get sufficient fake ID to get around that.
>
> See also: http://www.ahbl.org/funny/response1.php
>
> I'll let others here fill in the blanks.

:) :) :)

-- 
Ross Bamford - [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jargons of Info Tech industry

2005-10-13 Thread axel
In comp.lang.perl.misc Roedy Green <[EMAIL PROTECTED]> wrote:
> On Thu, 13 Oct 2005 01:17:45 -0400, Mike Meyer <[EMAIL PROTECTED]> wrote
 
>>No, that's what makes email a vector for infection. What makes using
>>the address book - for whatever purpose - possible for viruses is
>>having an API that allows arbitrary code to access it. But you have to
>>have that API - your customers are going to insist that they be able
>>to use their address book from third party applications.
 
> An automated change of address is possible today. It would be LESS
> easy to pull off under the scheme I proposed that requires digital
> signatures.

How? I keep my address book on my Palm as I send mail from different
computers? I suspect many other people do as well.

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


Re: how to make this code faster

2005-10-13 Thread [EMAIL PROTECTED]
hello,

I found that scipy only works with python 2.3 or?

I don't know if the logic is correct:
1. loop inside loop uses a lot of resources
2. Numeric or Numpy can make program faster
3. It use kind of Array/Matrix analysis style
4. We have to change our algorithms so that Numeric or Numpy can help
us, Matrix style

Best Regards,
pujo

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


Re: installer for amd64 build of python?

2005-10-13 Thread magneticlemur
Martin,
>I'm not at all mystified. The operating system was only released
>after the release of Python 2.4, there is no official compiler
>available yet to the general public, and I don't have the hardware
>to test such a release.
>It's fairly likely that Python 2.5 will not see official AMD64
>Windows binaries, either.

Fair enough.  I wasn't complaining about the lack of an official build.
Just surprised that I couldn't find reports on attempts at unofficial
builds.

Thanks for the tips re VS2005.

Regards,
Mike

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


Re: Pass a tuple (or list) to a C wrapper function

2005-10-13 Thread Fredrik Lundh
Jeremy Moles wrote:

> Probably what you want to do though is just keep the tuple as is and
> iterate over it using the PySequence_* protocol:
>
> http://docs.python.org/api/sequence.html

I did post a complete and tested example a few days ago, which contained
code that showed how to do this.  a complete waste of time, of course.

 



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


RE: Scope problem with nested functions.

2005-10-13 Thread AddisonN
Thanks Fredrik, that's fixed it. Apologies for the lazy typing - should
have cut and pasted the whole thing.

-Original Message-
From: Fredrik Lundh [mailto:[EMAIL PROTECTED] 
Sent: 13 October 2005 08:55
To: python-list@python.org
Subject: Re: Scope problem with nested functions.

<[EMAIL PROTECTED]> wrote

> I'm having trouble resolving a scope problem. I have a module, called 
> from another script, with this structure:

the code you posted gives a syntax error.  if I fix that, and add some
boilerplate to call getCcyMappings from inside the parseFile function, I
get:

Traceback (most recent call last):
  File "script.py", line 19, in ?
parseFile(0, 0, 0)
  File "script.py", line 17, in parseFile
getCcyMappings()
  File "script.py", line 8, in getCcyMappings
ccyMappings['CAN'] = ['CAD'] # for example.
NameError: global name 'ccyMappings' is not defined

which tells you that there is no *global* variable named ccyMappings.

the ccyMappings variable in your example isn't a global variable; it's
local to the parseFile function, and can be accessed from that function
and any inner functions via normal lexical scoping rules (=access, but
not rebind).

however, the global statement tells Python that the given name is a
global variable, and that any attempts to access or rebind that variable
should be done at the global (=module) level.

if you remove the global statement, Python will look for variables using
ordinary lexical scoping, and things will work as expected.

 






**
This email and any files transmitted with it are confidential and
intended solely for the use of the individual or entity to whom they
are addressed. If you have received this email in error please notify
the system manager.
This footnote also confirms that this email message has been swept by
MIMEsweeper for the presence of computer viruses.
Information Technology International (ITI) +44 (0)20 7315 8500
**

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


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Diez B. Roggisch
Paul Rubin wrote:
> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
> 
>>AFAIK some LISPs do a similar trick to carry int values on
>>cons-cells. And by this tehy reduce integer precision to 28 bit or
>>something. Surely _not_ going to pass a regression test suite :)
> 
> 
> Lisps often use just one tag bit, to distinguish between an immediate
> object and a heap object.  With int/long unification, Python shouldn't
> be able to tell the difference between an immediate int and a heap int.

That particular implementation used 3 or 4 tag-bits. Of course you are 
right that nowadays python won't notice the difference, as larger nums 
get implicitely converted to a suitable representation. But then the 
efficiency goes away... Basically I think that trying to come up with 
all sorts of optimizations for rather marginal problems (number 
crunching should be - if a python domain at all - done using Numarray) 
simply distracts and complicates the code-base. Speeding up dictionary 
lookups OTOH would have a tremendous impact (and if I'm n ot mistaken 
was one of the reasons for the 30% speed increase  between 2.2 and 2.3)

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


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Fredrik Lundh
Tom Anderson wrote:

> In both smalltalk and python, every single variable contains a reference
> to an object - there isn't the object/primitive distinction you find in
> less advanced languages like java.
>
> Except that in smalltalk, this isn't true: in ST, every variable *appears*
> to contain a reference to an object, but implementations may not actually
> work like that.

Python implementations don't have to work that way either.  Please don't
confuse "the Python language" with "the CPython implementation" and with
other implementations (existing as well as hypothetical).

(fwiw, switching to tagging in CPython would break most about everything.
might as well start over, and nobody's likely to do that to speed up integer-
dominated programs a little...)

 



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


Re: Pythot doc problem: lambda keyword...

2005-10-13 Thread Jamie Border
"Pisin Bootvong" <[EMAIL PROTECTED]> wrote:
Xah Lee ?:
[...]
> Fuck the Python liers and ignorant fuckheads. Motherfucking don't know
> shit and yet lying thru their teeth with fanfare.
[...]
>  Xah
>  [EMAIL PROTECTED]
> ? http://xahlee.org/

[elided]

PB> BTW, you post to the wrong group.

No, I think c.l.l is exactly the place to discuss how to play many trumpets 
through one set of teeth.

In fact, I have a box of trumpets lying around somewhere...

Open wide, Xah!

Jamie 


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


Re: Setdefault bypasses __setitem__

2005-10-13 Thread Diez B. Roggisch
> The implementation is certainly a design decision. setdefault() could be
> implemented in terms of __set/getitem__() as
> 
> def setdefault(self, key, value=None):
> try:
> return self[key]
> except KeyError:
> self[key] = value
> return self[key]
> 
> I guess it's not done for performance reasons. 

Nope. What if you changed your default value? Then you'd have to update 
the whole dictionary - but without keeping track of the keys you placed 
the default value under that isn't possible. Which strikes me as 
more-than-marginal overhead - without any advantage (as using 
__setitem__ for the default value isn't something I consider being a 
missing feature...)

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


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Paul Rubin
"Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
> That particular implementation used 3 or 4 tag-bits. Of course you are
> right that nowadays python won't notice the difference, as larger nums
> get implicitely converted to a suitable representation. But then the
> efficiency goes away... Basically I think that trying to come up with
> all sorts of optimizations for rather marginal problems (number
> crunching should be - if a python domain at all - done using Numarray)

I don't think it's necessarily marginal.  Tagged ints can be kept in
registers, which means that even the simplest code that does stuff
with small integers becomes a lot more streamlined, easing the load on
both the Python GC and the cpu's memory cache.  Right now with the
bytecode interpreter, it probably doesn't matter, but with Pypy
generating native machine code, this kind of thing can make a real
difference.
-- 
http://mail.python.org/mailman/listinfo/python-list


Teaching Python, was: Re: is there any Python code for spatial tessellation?

2005-10-13 Thread Magnus Lycka
Shi Mu wrote:
> is there any course website about teaching python?
> for instance, some computer science courses website?

Your subject line wasn't very helpful...

See:
http://mcsp.wartburg.edu/zelle/python/
http://mail.python.org/pipermail/edu-sig/
http://tech.canterburyschool.org/pycon/
http://www.livewires.org.uk/python/
http://www.ibiblio.org/obp/thinkCSpy/
http://www.python-in-business.org/ep2005/talk.chtml?talk=4772&track=774
http://www.educationaltechnology.ca/dan/archives/2005/03/23/teaching-introductory-computer-science-with-python/
-- 
http://mail.python.org/mailman/listinfo/python-list


Reload the network configuration directly from a python sript ?

2005-10-13 Thread HIL

Hi everybody,

I wrote a python script to setup my network interface under Linux. To
perform it, I use directly from my python script external programs as
'ifconfig' and 'route' ans I fill the file /etc/resolv.conf with the good
nameserver IP. So, it it works and my network is up.

My problem is that when I use the function socket.gethostbyaddr just after
setting up the network and without getting out of my script, I get an
exception socket.herror. If I start my script again, now the function
socket.gethostbyaddr works correctly.

Python seems to load the network configuration at startup, and if network is
not set at this moment, it does not reload changes.

So, does someone know how to reload the network configuration directly from
my script without restarting it ?

Thanks by advance.

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


Re: Adding a __filename__ predefined attribute to 2.5?

2005-10-13 Thread Fredrik Lundh
Rune Strand wrote:

>> those modules are already imported when Python gets to your code, so
>> the only "overhead" you're saving is a little typing.
>
> I don't understand this. Could you please elaborate?  - if sys or os
> are not imported for any other causes how are they already imported?

because they are imported for Python's own purposes, together with lots
of other stuff:

> python
Python 2.4.2
>>> import sys
>>> sys.modules.keys()
['copy_reg', 'locale', '__main__', 'site', '__builtin__', 'encodings', 
'os.path'
, 'encodings.cp437', 'encodings.codecs', 'ntpath', 'UserDict', 
'encodings.except
ions', 'nt', 'stat', 'zipimport', 'warnings', 'encodings.types', '_codecs', 
'enc
odings.cp1252', 'sys', 'codecs', 'types', '_locale', 'signal', 'linecache', 
'enc
odings.aliases', 'exceptions', 'os']

(sys is a built-in module, btw, so the cost of importing that is always close 
to zero)

> It may be lousy, but it requires no imports. And, as I said in the
> answer to Steve, I _know_ there are many ways to achieve this,
> including yours. But in your rush to pin-point lousy code, you didn't
> read that, I suppose.

you know, being clueless is one thing, but being both clueless and arrogant is
not a good way to get anywhere.  I suggest spending more time learning things
(start with the language reference), and less time picking fights that leads no-
where.

 



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


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Paul Rubin
"Fredrik Lundh" <[EMAIL PROTECTED]> writes:
> (fwiw, switching to tagging in CPython would break most about
> everything.  might as well start over, and nobody's likely to do
> that to speed up integer- dominated programs a little...)

Yeah, a change of that magnitude in CPython would be madness, but
the question is well worth visiting for PyPy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Steve Holden
Paul Rubin wrote:
> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
> 
>>That particular implementation used 3 or 4 tag-bits. Of course you are
>>right that nowadays python won't notice the difference, as larger nums
>>get implicitely converted to a suitable representation. But then the
>>efficiency goes away... Basically I think that trying to come up with
>>all sorts of optimizations for rather marginal problems (number
>>crunching should be - if a python domain at all - done using Numarray)
> 
> 
> I don't think it's necessarily marginal.  Tagged ints can be kept in
> registers, which means that even the simplest code that does stuff
> with small integers becomes a lot more streamlined, easing the load on
> both the Python GC and the cpu's memory cache.  Right now with the
> bytecode interpreter, it probably doesn't matter, but with Pypy
> generating native machine code, this kind of thing can make a real
> difference.

Until someone does the experiment this stuff is bound to be speculation 
(what's that saying about "premature optimization"?). But I can foresee 
that there'd be problems at the outer edges of the language: for 
example, sys.maxint would have to be reduced, and this in turn would 
lead to reduction in, for example, the theoretical maximum length of 
sequences.

Even if it reduced the average execution time of the "average" program, 
this will involve trade-offs which can only be fully appreciated in the 
light of practical experience.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Setdefault bypasses __setitem__

2005-10-13 Thread Peter Otten
Diez B. Roggisch wrote:

>> The implementation is certainly a design decision. setdefault() could be
>> implemented in terms of __set/getitem__() as
>> 
>> def setdefault(self, key, value=None):
>> try:
>> return self[key]
>> except KeyError:
>> self[key] = value
>> return self[key]
>> 
>> I guess it's not done for performance reasons.
> 
> Nope. What if you changed your default value? Then you'd have to update
> the whole dictionary - but without keeping track of the keys you placed
> the default value under that isn't possible. Which strikes me as
> more-than-marginal overhead - without any advantage (as using
> __setitem__ for the default value isn't something I consider being a
> missing feature...)

Are we talking about the same setdefault()?

setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

There is no per-instance default value just on per call:

>>> d = {}
>>> d.setdefault("a", 1)
1
>>> d.setdefault("a", 42)
1

I'm sure there is a misunderstanding in our conversation, I'm just not able
to nail it...

Peter




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


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Paul Rubin
Steve Holden <[EMAIL PROTECTED]> writes:
> Until someone does the experiment this stuff is bound to be
> speculation (what's that saying about "premature optimization"?). 

40 years of practical Lisp implementation efforts and around the globe
and hundreds of published papers on the subject might not be directly
Python-specific, but they're not what I'd call a total vacuum of
experimental results.

> But I can foresee that there'd be problems at the outer edges of the
> language: for example, sys.maxint would have to be reduced, and this
> in turn would lead to reduction in, for example, the theoretical
> maximum length of sequences.

if we're talking about 1 tag bit, sys.maxint would be 2**30-1 at the
lowest, which means the objects in the sequence would have to be
smaller than 4 bytes each if more than sys.maxint of them are supposed
to fit in a 32-bit address space.  Since we're using 4-byte pointers,
that can't happen.  We may have a worse problem by running out of
virtual address space if we use a copying GC.  Of course, on a 64-bit
cpu, this all becomes irrelevant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Setdefault bypasses __setitem__

2005-10-13 Thread Fredrik Lundh
Peter Otten wrote:

> Are we talking about the same setdefault()?
>
> setdefault(...)
>D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

note that it might be spelled "setdefault", but it should be pronounced
"get or set".

 



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


Re: Here I am again, same old arguments

2005-10-13 Thread gene tani
google "cheat sheet" or "quick reference"

http://rgruet.free.fr/#QuickRef
http://infohost.nmt.edu/tcc/help/pubs/python22/
http://www.onlamp.com/pub/a/python/excerpt/PythonPocketRef/index.html
http://diveintopython.org/appendix/abstracts.html
http://www.yukoncollege.yk.ca/~ttopper/COMP118/rCheatSheet.html
http://www.onlamp.com/python/excerpt/PythonPocketRef/examples/python.pdf


http://www.petefreitag.com/item/455.cfm
http://diveintopython.org/appendix/tips.html



> 3) Where do I find a command list, with syntax and all that fun stuff for 
> Python? I've explored
> the python site to no end, but I can't seem to find a list.
>

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


Re: Setdefault bypasses __setitem__

2005-10-13 Thread Duncan Booth
Diez B. Roggisch wrote:

> So if setdefault
> was implemented as
> 
> def setdefault(self, v):
>  self["SOME_DEFAULT_KEY_NAME"] = v

if setdefault was implemented that way then all current uses of setdefault 
would throw an exception.

setdefault takes *three* parameters: self, key, value. Once you include the 
key parameter your entire argument implodes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for a Python mentor

2005-10-13 Thread Nir Aides
Hello Len,

You should try the #python IRC room.
It is always very active and helpful.

Nir



LenS wrote:
> Hello
> 
> Was wandering if there is any place where some one could go to get
> mentoring on python coding.  I have started coding in python but I am
> the only one in the shop  using it.  So there is no one around to look
> over my code give suggestions on improvement, in style, logic, easier
> ways of doing things etc.  I am not really looking for hand holding as
> much mentoring.  I have purchased about every python book out and have
> a list a mile long on my internet bookmarks.  I believe I have a good
> grasp of the fundamentals procedurally and I am fighting my way through
> OOP.  I am more at the stage of trying to pull things together into
> programs that perform real world tasks.  At one point I thought I saw
> some place on one of the web site that did this kind of thing but I
> can't find it now.
> 
> Any help or suggestions welcomed
> Len Sumnler
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for a Python mentor

2005-10-13 Thread Kent Johnson
LenS wrote:
> Hello
> 
> Was wandering if there is any place where some one could go to get
> mentoring on python coding.  I have started coding in python but I am
> the only one in the shop  using it.  So there is no one around to look
> over my code give suggestions on improvement, in style, logic, easier
> ways of doing things etc.  

I second gene's recommendation of the python-tutor mailing list - we do all of 
the above as well as cheerfully answer all questions, give suggestions on how 
to do things, etc.

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


Re: Setdefault bypasses __setitem__

2005-10-13 Thread Diez B. Roggisch

> Are we talking about the same setdefault()?
>
>
> D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
>
> There is no per-instance default value just on per call:

Oh. You're right. I was somehow under the impression that setdefault is
per-instance, so that I can avoid

d.get(key, default)

and write

d[key]

instead, for all keys, and get no more KeyErrors. But then you are
right of course.

Regards,

Diez

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


Re: Here I am again, same old arguments

2005-10-13 Thread Steven D'Aprano
On Thu, 13 Oct 2005 08:05:00 +, CJ wrote:

> 1) Why no global variables? I'm taking your word for it that they're bad. Far 
> be it from me to 
> argue with you, but why are they bad ideas to begin with? Most of the 
> languages I've used up to 
> this point have been reliant on globals, so I'm not entirely sure why they 
> shouldn't be used.

Global variables aren't *entirely* bad. I use them myself, sometimes for
constants (well, pseudo-constants -- Python doesn't enforce constants) and
short, quick 'n' dirty throw away code.

But in general, as your code gets bigger and more complicated, using
global variables gets more dangerous, unreliable, harder to debug, and
generally a bad idea. Let me show you some examples.

Suppose you have some some code like this:

# set a global variable
gParrot = 1
# do some work with it
get_shrubbery()
eat_after_dinner_mint()
make_machine_go_ping()
pine_for_the_fjords()
print gParrot

(The names come from Monty Python, as is traditional in Python.)

You have four functions in that piece of code. You expect that after
the four functions run, the code should print 2, but instead it prints
3. Why? Somehow, parrot is getting set to the wrong value. 

Which of those four functions is to blame? Which ones use the global
variable parrot? You can't tell just by looking. Which ones change the
variable? Again, you can't tell. The only way to find out is to read the
code. In a big program, there might be thousands of functions, split over
dozens of modules. Just going backwards and forwards looking up the
functions is hard work.

Now let's re-write that code properly:

# set a variable
parrot = 1
# do some work with it
get_shrubbery(parrot)
parrot = eat_after_dinner_mint()
make_machine_go_ping()
parrot = pine_for_the_fjords()
print parrot

Now it is easier to see what is going on. get_shrubbery uses the value of
parrot, but can't change it. Or rather, if it changes parrot, that change
is local to the function, and doesn't effect anything outside of that
function. So it isn't responsible for the bug.

The machine that goes ping doesn't even use the value of parrot, and it
certainly doesn't change it. So it can't be responsible for the bug.

The value of parrot gets changed in only two places, once by
eat_after_dinner_mint, and the other by pine_for_the_fjords. So you have
halved the amount of places that you need to look for the bug.

What else is wrong with globals?

(1) You can't be sure what a function does without reading and
understanding every bit of code. Suppose you have a function that is
supposed to make the machine go ping, and return True if the machine
pinged and False if it didn't. But you don't know if it changes any global
variables -- that is what we call a "side-effect". Like side-effects in
medicine, it makes it very hard to tell what a function will do.

(2) Global variables allow indiscriminate access. You can't prevent other
functions from messing them up. If you are writing a small program on your
own, maybe you can trust yourself not to accidentally mangle the global
variable. But if you are working on a big project with ten other
programmers, and they all are writing code that reads and writes to your
global variables, can you really trust that none of them will put the
wrong value there?

(3) Globals make it really hard to change your code. You have a global
variable and you want to change what it stands for. But you can't, because
all these dozens of other functions rely on it. So you end up leaving the
old global there, and inventing a new one, and now you have twice as many
places that bugs can be hiding because every function can potentially mess
up two globals instead of one.

(4) It is easy to screening globals accidentally, a source of bugs. You
have a global called "parrot", but somewhere in a function you create a
local variable also called "parrot". Now you have lost access to the
global. This can be a source of many puzzling bugs.

(5) Dependency: global variables mean that different functions and modules
depend on each other in ways that are very hard to control. This means
that any time you modify a function that uses globals, you could
potentially be breaking *any other function*, even if the change you made
to the first function is not a bug.

(6) Error propagation. A bug in one function will propagate to other
functions. This can mean that you detect the bug in a piece of code a
long, long way away from where the bug was introduced. 



> 2) Why no for loop with an index? Again, far be it from me to argue, but it 
> seemed perfect for 
> my program. 

Why do work that you don't have to?

You are writing code like this:

myList = ["spam", "ping", "parrot", "fjords"]
for indx in range(len(myList)):
print myList[indx],

It prints:
spam ping parrot fjords

But look at how much work you have to do: first you count the length of
the list with len(myList), then you create a list of integers between 0
and that length with range, then for each 

Re: Pass a tuple (or list) to a C wrapper function

2005-10-13 Thread Java and Swing
Fredrik...I forgot about that...wish Google Groups had a way to quickly
find the topics a user posts.

anyhow, for receiving an object from python..is it

ok = PyArg_ParseTuple(args, "sO", &x, &y);

...is it "sO" or "s0" is it O (as in the letter) or 0 (as in the
number)?  I would think "O" the letter..but it looks like a zero.

thanks

Fredrik Lundh wrote:
> Jeremy Moles wrote:
>
> > Probably what you want to do though is just keep the tuple as is and
> > iterate over it using the PySequence_* protocol:
> >
> > http://docs.python.org/api/sequence.html
>
> I did post a complete and tested example a few days ago, which contained
> code that showed how to do this.  a complete waste of time, of course.
> 
> 

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


graphic memory & animation

2005-10-13 Thread Peres



Hello!
Python is great!... but the erasing of the graphic 
memory is slow (I used surf.fill from Pygame).
Does anyone know how to erase the screen faster, in 
animated graphics?
 
With many thanks
 
Valerie Peres
 
-- 
http://mail.python.org/mailman/listinfo/python-list

wxPython question

2005-10-13 Thread vpr
Hi

Does anyone have some example code to create a wx dialog that apears
off screen on the bottom right hand corner and slides up into the
screen ?

Thanx

/vpr

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


Re: Multiple assignments simplification

2005-10-13 Thread bearophileHUGS
Thank you George Sakkis for your fast and accurate answer. In my life I
am encountering lot of graph-based solutions to my problems. I'll try
to implement your solution as soon as possible.


Fredrik Lundh>working on a Python to C/C++ translator without knowing
what kind of optimizations a C/C++ compiler can do for you sounds like
a great way to waste your time...<

I am not the author of ShedSkin (Mark Dufour), I'm ignorant, he is much
more expert than me about C++. So the possibile waste of time is just
mine.

Some experimental timings have shown me that different C++ compilers
have different optimization capabilities, and such experiments show me
that sometimes they (g++ of MinGW) aren't capable of doing some
"obvious" optimizations (I haven't tested the assignments yet).


Fredrik Lundh>the interesting thing is where the values came from, and
what you're doing with the values later on. minimizing the number of
assignment statements in the swap translation won't change a thing...)<

I see. (It's just a detail, as I've said...)
If you Fredrik have some free time and you are interested, you can
probably help Mark Dufour improve that compiler. You can just email the
author or post things in the Sourceforge site, etc.

Bear hugs,
bearophile

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


Adding methods to an object

2005-10-13 Thread Gabriele *darkbard* Farina
Hi, there is a way to add methods to an object dynamically? I need to
do something like this. I remember python allowed this ...

class A(object):
 def do(s, m):
  print m

 @staticmethod
 def init(obj):
  obj.do = A.do

class Test(object):
 pass

o = Test()
A.init(o)

o.do(10)

Now it gives me an error ... unbound method ...

tnx, gabriele

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


Re: Pass a tuple (or list) to a C wrapper function

2005-10-13 Thread Java and Swing
Fredrik,
  ...I tried using your code...

static long *get_long_array(PyObject *data, int *data_size) {
int i, size;
long* out;
PyObject* seq;

seq = PySequence_Fast(data, "expected a sequence");
if (!seq)
return NULL;

size = PySequence_Size(seq);
if (size < 0)
return NULL;

if (data_size)
*data_size = size;

out = (long*) PyMem_Malloc(size * sizeof(long));
if (!out) {
Py_DECREF(seq);
PyErr_NoMemory();
return NULL;
}

for (i = 0; i < size; i++)
out[i] = PyInt_AsLong(PySequence_Fast_GET_ITEM(seq, i));

Py_DECREF(seq);

if (PyErr_Occurred()) {
PyMem_Free(out);
out = NULL;
}

return out;

}


and I get this error..

C:\project\myapp.c(549) : error C2040: 'get_long_array' : 'long
*(struct _object *,int *)' differs in levels of indirection from 'int
()'

any idea?

Fredrik Lundh wrote:
> Jeremy Moles wrote:
>
> > Probably what you want to do though is just keep the tuple as is and
> > iterate over it using the PySequence_* protocol:
> >
> > http://docs.python.org/api/sequence.html
>
> I did post a complete and tested example a few days ago, which contained
> code that showed how to do this.  a complete waste of time, of course.
> 
> 

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


Re: Adding a __filename__ predefined attribute to 2.5?

2005-10-13 Thread Alex Martelli
Rune Strand <[EMAIL PROTECTED]> wrote:

> Ok, Alex. I know a good explanation when I see one. Thanks!

You're welcome!  I've tried to give good (but shorter!-) explanations in
the Nutshell, too, but of course it's easier to aim a specific
explanation to a specific questioner than to try and clarify
"everything" for "everybody" (particularly because, when posting, I'm
not forced to be concise as I am when writing books or articles, so I
can aim more relentlessly for completeness and precision...).


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


Re: wxPython question

2005-10-13 Thread Will McGugan
vpr wrote:
> Hi
> 
> Does anyone have some example code to create a wx dialog that apears
> off screen on the bottom right hand corner and slides up into the
> screen ?
> 

Andrea Gavana does..

http://xoomer.virgilio.it/infinity77/eng/freeware.html#toasterbox

Will McGugan
-- 
http://www.willmcgugan.com
"".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in 
"jvyy*jvyyzpthtna^pbz")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding methods to an object

2005-10-13 Thread bearophileHUGS
This isn't code of mine, it's probably from the cookbook, maybe with
little changes:

| def addMethod(object, method, name=None):
| if name is None: name = method.func_name
| class newclass(object.__class__):
| pass
| setattr(newclass, name, method)
| object.__class__ = newclass

name is the name for the new method, if it's None then the name of
"method" is used.

Bye,
bearophile

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


Re: Pass a tuple (or list) to a C wrapper function

2005-10-13 Thread Java and Swing
I got it.   I had get_long_array placed after the method that was
calling it..
i.e.

void doStuf(...) {
   x = get_long_array(...);
}

static long *get_long_array(PyObject *data, int *data_size) {
...
}

...I put get_long_array before it in my code..and its fine.

Thanks

Java and Swing wrote:
> Fredrik,
>   ...I tried using your code...
>
> static long *get_long_array(PyObject *data, int *data_size) {
> int i, size;
> long* out;
> PyObject* seq;
>
> seq = PySequence_Fast(data, "expected a sequence");
> if (!seq)
> return NULL;
>
> size = PySequence_Size(seq);
> if (size < 0)
> return NULL;
>
> if (data_size)
> *data_size = size;
>
> out = (long*) PyMem_Malloc(size * sizeof(long));
> if (!out) {
> Py_DECREF(seq);
> PyErr_NoMemory();
> return NULL;
> }
>
> for (i = 0; i < size; i++)
> out[i] = PyInt_AsLong(PySequence_Fast_GET_ITEM(seq, i));
>
> Py_DECREF(seq);
>
> if (PyErr_Occurred()) {
> PyMem_Free(out);
> out = NULL;
> }
>
> return out;
>
> }
>
>
> and I get this error..
>
> C:\project\myapp.c(549) : error C2040: 'get_long_array' : 'long
> *(struct _object *,int *)' differs in levels of indirection from 'int
> ()'
>
> any idea?
>
> Fredrik Lundh wrote:
> > Jeremy Moles wrote:
> >
> > > Probably what you want to do though is just keep the tuple as is and
> > > iterate over it using the PySequence_* protocol:
> > >
> > > http://docs.python.org/api/sequence.html
> >
> > I did post a complete and tested example a few days ago, which contained
> > code that showed how to do this.  a complete waste of time, of course.
> > 
> > 

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


When to free memory for C wrapper?

2005-10-13 Thread Java and Swing
I have been posting lately about writing a C wrapper so Python can
access my C functions.

In my wrapper function I have something like...

static PyObject *wrap_doStuff(PyObject *self, PyObject *args) {
PyObject *data;
char *result;
long *d;

PyArg_ParseTuple(args, "O:wrap_doStuff", &data);

d = get_long_array(data);

result = doStuff(d);

return PyString_FromString(result);
}

Now, do I need to use PyMem_Free to free up the "PyObject *data"?

Thanks.

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


Re: When to free memory for C wrapper?

2005-10-13 Thread Java and Swing
One other thing, I was reading about Py_DECREF...and I see it says

"A safe approach is to always use the generic operations (functions
whose name begins with "PyObject_", "PyNumber_", "PySequence_" or
"PyMapping_"). These operations always increment the reference count of
the object they return. This leaves the caller with the responsibility
to call Py_DECREF() when they are done with the result; this soon
becomes second nature."
URL: http://www.python.org/doc/api/refcounts.html

So does that mean before my C wrapper function exits, or returns I
should Py_DECREF any PyObject's I have?  For example, in my previous
post in this thread..I would have to Py_DECREF(data) right?

What if in my wrapper I had

static PyObject *wrap_doStuff(...) {
PyObject *pyResult;

...

pyResult = PyString_FromString(...);

   return pyResult;
}

Is PyResult going to be de-referenced or handled automaticlly by python
in some way?  Or, do I need to somehow call Py_DECREF(pyResult)
somewhere..if so, where/when?

Thanks!

Java and Swing wrote:
> I have been posting lately about writing a C wrapper so Python can
> access my C functions.
>
> In my wrapper function I have something like...
>
> static PyObject *wrap_doStuff(PyObject *self, PyObject *args) {
> PyObject *data;
> char *result;
> long *d;
>
> PyArg_ParseTuple(args, "O:wrap_doStuff", &data);
>
> d = get_long_array(data);
>
> result = doStuff(d);
>
> return PyString_FromString(result);
> }
>
> Now, do I need to use PyMem_Free to free up the "PyObject *data"?
> 
> Thanks.

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


Re: Adding methods to an object

2005-10-13 Thread rcramsdell
gabriele,

This works (A, Test, and o as defined by you):

>>> a=A()
>>> o.do(a, 10)
10

Your problem is that do() really has two parameters, an A instance and
whatever you want to print.

Why not do this:

>>> def newdo(m):
... print m
...
>>> newdo(10)
10
>>> o=Test()
>>> o.newdo = newdo
>>> o.newdo(10)
10

Robert

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


Re: Adding methods to an object

2005-10-13 Thread Steven D'Aprano
On Thu, 13 Oct 2005 06:06:20 -0700, Gabriele *darkbard* Farina wrote:

> Hi, there is a way to add methods to an object dynamically? 

Yes. There are three different sorts of methods, and three ways of adding
them.

py> class Parrot:
... def __init__(self):
... pass
py> # Parrot is the class.
py> # Parrot() is an instance of the class.

Firstly, you want an ordinary method with a "self" parameter, as if you
had defined it when you created the class.


py> def spam(self):
... return "Spam comes from %s" % self
... 
py> Parrot.spam = spam

Now we try calling it from an instance:

py> Parrot().spam()
'Spam comes from <__main__.Parrot instance at 0xed498fec>'

If you try to call spam direct from the class, it fails:

py> Parrot.spam()
TypeError: unbound method spam() must be called with Parrot instance as
first argument (got nothing instead)



The second way of adding a method is a class method. Class methods don't
know about the instance you call them from, only the class.

py> def fjords(cls):
... return "I'm pining for the fjords at %s." % cls
... 
py> Parrot.fjords = classmethod(fjords)

Now we can call it from either the class or any instance, and get the
exact same result. fjords just can't see the instance, only the class:

py> Parrot.fjords()
"I'm pining for the fjords at __main__.Parrot"
py> Parrot().fjords()
"I'm pining for the fjords at __main__.Parrot"



Lastly, we can add a static method, that doesn't know about either the
class or the instance:

py> def ham():
... return "Genuine pig product." 
... 
py> Parrot.ham = staticmethod(ham)
py> Parrot.ham()
'Genuine pig product'
py> Parrot().ham()
'Genuine pig product'



Summary:

If you write the function with a "self" argument, and just add it to the
class, you must call that method using an instance. This is an ordinary
instance method, as if you had created the class with it.

If you write the function with a "cls" argument, you must add it to the
class with a classmethod() call, and then call it from either the class or
an instance. This method cannot access the instance that calls it, only
the class.

If you write the function without a "self" or "cls" argument, you must add
it to the class with a staticmethod() call. This method cannot access
either the class or the instance object.



-- 
Steven.

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


Re: how to make this code faster

2005-10-13 Thread George Sakkis
<[EMAIL PROTECTED]> wrote:

> hello,
>
> I found that scipy only works with python 2.3 or?

You can use Numeric instead of scipy if you need/want to:

from Numeric import arange,reshape,sin

def computeMatrix(n):
xcoor = arange(0,1,1/float(n))
ycoor = reshape(xcoor, (n,1))
return sin(xcoor*ycoor) + 8*xcoor

Note that arange() does not include the endpoint, i.e. 
arange(0,1,0.25).tolist() ==[0.0, 0.25, 0.5,
0.75].

> I don't know if the logic is correct:
> 1. loop inside loop uses a lot of resources
> 2. Numeric or Numpy can make program faster
> 3. It use kind of Array/Matrix analysis style
> 4. We have to change our algorithms so that Numeric or Numpy can help
> us, Matrix style

That's correct more or less.

George


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


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Alex Martelli
Tom Anderson <[EMAIL PROTECTED]> wrote:

> On Tue, 11 Oct 2005, Alex Martelli wrote:
> 
> > Tom Anderson <[EMAIL PROTECTED]> wrote:
> >   ...
> >> Has anyone looked into using a real GC for python? I realise it would be a
> >
> > If you mean mark-and-sweep, with generational twists,
> 
> Yes, more or less.
> 
> > that's what gc uses for cyclic garbage.
> 
> Do you mean what python uses for cyclic garbage? If so, i hadn't realised

Yes, gc (a standard library module) gives you access to the mechanism
(to some reasonable extent).

> that. There are algorithms for extending refcounting to cyclic structures
> (i forget the details, but you sort of go round and experimentally 
> decrement an object's count and see it ends up with a negative count or
> something), so i assumed python used one of those. Mind you, those are
> probably more complex than mark-and-sweep!

Not sure about that, when you consider the "generational twists", but
maybe.


> >> lot more complexity in the interpreter itself, but it would be faster,
> >> more reliable, and would reduce the complexity of extensions.
> >
> > ???  It adds no complexity (it's already there), it's slower,
> 
> Ah. That would be why all those java, .net, LISP, smalltalk and assorted
> other VMs out there, with decades of development, hojillions of dollars
> and the serried ranks of some of the greatest figures in computer science
> behind them all use reference counting rather than garbage collection,
> then.
> 
> No, wait ...

Not everybody agrees that "practicality beats purity", which is one of
Python's principles.  A strategy based on PURE reference counting just
cannot deal with cyclic garbage -- you'd also need the kind of kludges
you refer to above, or a twin-barreled system like Python's.  A strategy
based on PURE mark-and-sweep *CAN* be complete and correct... at the
cost of horrid delays, of course, but what's such a practical
consideration to a real purist?-)

In practice, more has probably been written about garbage collection
implementations than about almost every issue in CS (apart from sorting
and searching;-).  Good techniques need to be "incremental" -- the need
to "stop the world" for unbounded amounts of time (particularly in a
paged virtual memory world...), typical of pure m&s (even with
generational twists), is simply unacceptable in all but the most "batch"
type of computations, which occupy a steadily narrowing niche.
Reference counting is intrinsically "reasonably incremental"; the
worst-case of very long singly-linked lists (such that a dec-to-0 at the
head causes a cascade of N dec-to-0's all along) is as rare in Python as
it is frequent in LISP (and other languages that go crazy with such
lists -- Haskell, which defines *strings* as single linked lists of
characters, being a particularly egregious example) [[admittedly, the
techniques for amortizing the cost of such worst-cases are well known in
any case, though CPython has not implemented them]].

In any case, if you like Python (which is a LANGUAGE, after all) and
don't like one implementation of it, why not use a different
implementation, which uses a different virtual machine?  Jython, for the
JVM, and IronPython, for MSCLR (presumably what you call ".net"), are
quite usable; project pypy is producing others (an implementation based
on Common LISP was one of the first practical results, over a year ago);
not to count Parrot, and other projects yet...


> > it is, if anything, LESS reliable than reference counting (which is way
> > simpler!),
> 
> Reliability is a red herring - in the absence of ill-behaved native 
> extensions, and with correct implementations, both refcounting and GC are
> perfectly reliable. And you can rely on the implementation being correct,
> since any incorrectness will be detected very quickly!

Not necessarily: tiny memory leaks in supposedly "stable" versions of
the JVM, for example, which get magnified in servers operating for
extremely long times and on very large scales, keep turning up.  So, you
can't count on subtle and complicated implementations of garbage
collection algorithms being correct, any more than you can count on that
for (for example) subtle and complicated optimizations -- corner cases
can be hidden everywhere.

There are two ways to try to make a software system reliable: make it so
simple that it obviously has no bugs, or make it so complicated that it
has no obvious bugs.  RC is definitely tilted towards the first of the
two options (and so would be mark-and-sweep in the pure form, the one
where you may need to stop everything for a LONG time once in a while),
while more sophisticated GC schemes get more and more complicated.

BTW, RC _IS_ a form of GC, just like, say, MS is.


> > and (if generalized to deal with ALL garbage) it might make it almost
> > impossible to write some kinds of extensions (ones which need to 
> > interface existing C libraries that don't cooperate with whatever GC
> > collection you choose).
> 
> Lucky those

How to call a script from another?

2005-10-13 Thread Christian
 From a not even newbie:

Without knowing much about Python (yet) I'm trying to install the CMS 
Zope via FTP (with the well documented changes to make it work on an 
Apache server).
By birth Zope is started from a shell script. And not having the 
permissions to execute such ones I'll try writing a .py script (with the 
shebang that I allready knows will do the job) to call another .py 
script like the original shell script does.

So my question is:
How do I call a .py script from another .py script?
(Writing the rest - I hope - is piece of cake ;-) ).

(And yes, I know that there are a lot of other problems but for starters 
I just would like to try to call a .py script from another .py script.)


Thanks

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


Re: Perl-Python-a-Day: Sorting

2005-10-13 Thread Lasse Vågsæther Karlsen
Diez B. Roggisch wrote:

> Diez
> 
> [1] http://xahlee.org/PageTwo_dir/Personal_dir/mi_pixra.html

Oh man... Talk about ... bummer.

Seriously, who do we call to get someone with a straightjacket to show 
up at his home?

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list

Your message to Trasno awaits moderator approval

2005-10-13 Thread trasno-bounces
Your mail to 'Trasno' with the subject

Re: Your letter

Is being held until the list moderator can review it for approval.

The reason it is being held:

SpamAssassin identified this message as possible spam (score 3)

Either the message will get posted to the list, or you will receive
notification of the moderator's decision.  If you would like to cancel
this posting, please visit the following URL:


http://ceu.fi.udc.es/cgi-bin/mailman/confirm/trasno/dd18e8bb5cc9d685d0ef2dedb7b539562d988d39

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


Well written open source Python apps

2005-10-13 Thread Ben
Could anyone suggest an open source project that has particularly well
written Python?  I am especially looking for code that people would
describe as "very Python-ic".  (Not trying to start any kind of war -
just wanted some good examples of a well written Python app to read.)

Thanks!
-Ben

P.S. - Sorry if this has been discussed at length before - I searched
the group before I posted, but didn't come up with what I was looking
for.

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


Re: How to call a script from another?

2005-10-13 Thread Jaime Wyant
I think this is the simplest way to do that:

import sys
sys.path.append('/path/to/directory/containg/script')

import zopescript
zopescript.main()

The code above assumes:
o that the path you use to append contains an __init__.py in it...
o zopescript is the module you want to `run'
o main is the method in zopescript that cranks up zope.

I'm not sure of how to do it the hard way...

jw

On 10/13/05, Christian <[EMAIL PROTECTED]> wrote:
>  From a not even newbie:
>
> Without knowing much about Python (yet) I'm trying to install the CMS
> Zope via FTP (with the well documented changes to make it work on an
> Apache server).
> By birth Zope is started from a shell script. And not having the
> permissions to execute such ones I'll try writing a .py script (with the
> shebang that I allready knows will do the job) to call another .py
> script like the original shell script does.
>
> So my question is:
> How do I call a .py script from another .py script?
> (Writing the rest - I hope - is piece of cake ;-) ).
>
> (And yes, I know that there are a lot of other problems but for starters
> I just would like to try to call a .py script from another .py script.)
>
>
> Thanks
>
> Chris
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


cgi python

2005-10-13 Thread Python_it
I going to use the cgi-handler (mod_python):

http://www.modpython.org/live/mod_python-3.2.2b/doc-html/hand-cgi.html


If I test a simply py script it works

code:
===
print "Content-type: text/html\n"
print """


TEST


"""


But if I test a py script with cgi comments (import cgi):

Part of the code

import cgi

#get HTTP query parameters
query = cgi.FieldStorage()

#Get the selected year and month
selectedYear = int(query["year"].value)
selectedMonth = int(query["x"].value) + 1

#Get the monthly revenue
monthlyRevenue = float(query["value"].value)


I get the following error:

errormessage:
==
Mod_python error: "PythonHandler mod_python.cgihandler"

Traceback (most recent call last):

  File "C:\Program
Files\Python24\Lib\site-packages\mod_python\apache.py", line 299, in
HandlerDispatch
result = object(req)

  File "C:\Program
Files\Python24\Lib\site-packages\mod_python\cgihandler.py", line 96, in
handler
imp.load_module(module_name, fd, path, desc)

  File "C:/Program Files/Apache
Group/Apache2/htdocs/clue/modules/templates\clickpie.py", line 9, in ?
selectedYear = int(query["year"].value)

  File "C:\Program Files\Python24\Lib\cgi.py", line 559, in __getitem__
raise KeyError, key

KeyError: 'year'


Who can help me?

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


Re: Pass a tuple (or list) to a C wrapper function

2005-10-13 Thread Fredrik Lundh
Java and Swing wrote:

> and I get this error..
>
> C:\project\myapp.c(549) : error C2040: 'get_long_array' : 'long
> *(struct _object *,int *)' differs in levels of indirection from 'int
> ()'

so what's on line 549 in myapp.c?

what other warnings did you get from the compiler?

do you have other things named "get_long_array" in your program ?

(I'm really beginning to think that you should take a break and learn
a little more C before continuing on this task; C isn't that hard, but
it's not really a language you can use to write programs by trial and
error...)





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


Re: cgi python

2005-10-13 Thread Christian Hausknecht
Python_it wrote:

> I going to use the cgi-handler (mod_python):
> 
> http://www.modpython.org/live/mod_python-3.2.2b/doc-html/hand-cgi.html
> 
> 
> If I test a simply py script it works
> 
> code:
> ===
> print "Content-type: text/html\n"
> print """
> 
> 
> TEST
> 
> 
> """
> 
> 
> But if I test a py script with cgi comments (import cgi):
> 
> Part of the code
> 
> import cgi
> 
> #get HTTP query parameters
> query = cgi.FieldStorage()
> 
> #Get the selected year and month
> selectedYear = int(query["year"].value)
> selectedMonth = int(query["x"].value) + 1
> 
> #Get the monthly revenue
> monthlyRevenue = float(query["value"].value)
> 
> 
> I get the following error:
> 
> errormessage:
> ==
> Mod_python error: "PythonHandler mod_python.cgihandler"
> 
> Traceback (most recent call last):
> 
>   File "C:\Program
> Files\Python24\Lib\site-packages\mod_python\apache.py", line 299, in
> HandlerDispatch
> result = object(req)
> 
>   File "C:\Program
> Files\Python24\Lib\site-packages\mod_python\cgihandler.py", line 96, in
> handler
> imp.load_module(module_name, fd, path, desc)
> 
>   File "C:/Program Files/Apache
> Group/Apache2/htdocs/clue/modules/templates\clickpie.py", line 9, in ?
> selectedYear = int(query["year"].value)
> 
>   File "C:\Program Files\Python24\Lib\cgi.py", line 559, in __getitem__
> raise KeyError, key
> 
> KeyError: 'year'
> 
> 
> Who can help me?
There is no Parameter 'year' in the Format-String sent by the Webserver!
You can test it like this:
if(query.has_key("yaer")):
xyz = query["year"].value

If you want to get a Parameter called 'year', you must call the cgi-Script
like this:
http://host/path-to-cgi-dir/script.py?year=2005

Another method is, to use a form in the calling html-Page and put a hidden
value into it.

Ciao,
Christian

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


Re: Jargons of Info Tech industry

2005-10-13 Thread Mike Meyer
Roedy Green <[EMAIL PROTECTED]> writes:
> On Thu, 13 Oct 2005 01:32:03 -0400, Mike Meyer <[EMAIL PROTECTED]> wrote
> or quoted :
>>That won't prevent phishing, that will just raise the threshhold a
>>little. The first hurdle you have to get past is that most mail agents
>>want to show a human name, not some random collection of symbols that
>>map to a unique address. Even if you do that, most readers aren't
>>going to pay attention to said random collection of symbols. Given
>>that, there are *lots* of tricks that can be used to disguise the
>>signed name, most of which phishers are already using. How many people
>>do you think will really notice that mail from "John Bath, PayPal
>>Customer Service Representative" ([EMAIL PROTECTED]) isn't really
>>from paypal?
>
> I think it better than you imagine.  
>
> First of all Mr. Phish will come in as a new communicant begging an
> audience. That is your first big clue. PayPal is already allowed in.

That's your first big clue. You've got two problems, though.

1) An as yet unspecified mechanism that magically approves everyone
   that you want to talk to. That's a big lump to swallow. It's also
   not an easy problem - all existing mechanisms for approving people
   require constant attention. Casual users aren't going to put up
   with that.

2) What makes you think your average user will realize this? It only
   takes a few percent to make it worth the phishers time.

> Next if Thawte issues certs, they won't allow Phish names such as
> Paypol.com just as now for other certs.

So they'll do what their web sites do now, and sign their own certs.

> Mr. Phish is coming in on a different account. 

Different from what? And how does the user get told about this, and
what will make them care?

> Next Mr. Phish had to present his passport etc when he got his Thawte
> ID.  Now Interpol has a much better handle on putting him in jail.

Not if he didn't have to go to Thawte.

  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: cgi python

2005-10-13 Thread Paul Boddie
Python_it wrote:
> I going to use the cgi-handler (mod_python):
>
> http://www.modpython.org/live/mod_python-3.2.2b/doc-html/hand-cgi.html
>
> If I test a simply py script it works

You don't say how you test it, but I imagine that you just point your
browser to the location where the program is published, without
specifying any query parameters - see below for the significance of
this.

[...]

> But if I test a py script with cgi comments (import cgi):
>
> Part of the code
> 
> import cgi
>
> #get HTTP query parameters
> query = cgi.FieldStorage()
>
> #Get the selected year and month
> selectedYear = int(query["year"].value)

[...]

> KeyError: 'year'

The problem is that if you point your browser to this new program and
don't specify query parameters (eg. ?year=2005&x=10&value=5000 on the
end of the URL) then attempting to get the "year" parameter from the
query object will fail because the parameter doesn't exist - you didn't
specify it.

What you should do is to test for its presence first, just like you
would with a normal Python dictionary, and I believe that the query
object supports the has_key method:

if query.has_key("year"):
selectedYear = int(query["year"].value)

A more comprehensive alternative, given that the "year" parameter may
not be a number, is to catch any exceptions raised when you try and get
the parameter's value:

try:
selectedYear = int(query["year"].value)
except KeyError:
Do something here about the missing parameter.
except ValueError:
Do something here about a non-integer parameter.

Testing Web applications can be hard, but the traceback tells you
everything you need to know here.

Paul

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


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Scott David Daniels
Paul Rubin wrote:
> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
(about tag bits)
 >>... Basically I think that trying to come up with all sorts of
 >> optimizations for rather marginal problems (number crunching
 >> should be - if a python domain at all - done using Numarray)
> I don't think it's necessarily marginal.  Tagged ints can be kept in
> registers, which means that even the simplest code that does stuff
> with small integers becomes a lot more streamlined, easing the load on
> both the Python GC and the cpu's memory cache
But the cost on modern computers is more problematic to characterize.
Current speeds are due to deep pipelines, and a conditional in the
INCREF code would blow a pipeline.  On machines with a conditional
increment instruction (and a C (or whatever) compiler clever enough to
use it, saving the write saves dirty cache in the CPU, but most of
today's CPU/compiler combos will flush the pipeline, killing a number
of pending instructions.

> Right now with the bytecode interpreter, it probably doesn't matter,
> but with Pypy generating native machine code, this kind of thing can
> make a real difference.
You are right that Pypy is the place to experiment with all of this.
That project holds a lot of promise for answering questions that seem
to otherwise degenerate into "Jane, you ignorant slut" (for non-US
readers, this is a reference to an old "Saturday Night Live" debate
skit where the debate always degenerated into name-calling).

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing lists

2005-10-13 Thread jon

To take the heat out of the discussion:

sets are blazingly fast.

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


passing variable arguments to a function

2005-10-13 Thread Ryan Wilcox
Hello all,

I want to be able to pass a variable number of parameters into a Python
function. Now, I know how to _receive_ variable arguments, but I don't
know how to _send_ them.

def myFunction(*args):
print args

myList = [1, 2, 3, 4]
myFunction(myList)

this function will print out ([1, 2, 3, 4]).

Except that's not what I want. I want the equivalent to:

myFunction(1, 2, 3, 4)

So, given an array, how can I unpack the array and pass all of the
elements into a Python function as parameters?

Thanks in advance!,
_Ryan Wilcox

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


Re: graphic memory & animation

2005-10-13 Thread Fredrik Lundh
"Peres" wrote:

> Python is great!... but the erasing of the graphic memory is slow (I used
> surf.fill from Pygame).

define slow.

> Does anyone know how to erase the screen faster, in animated graphics?

if you're doing animation on modern hardware, there's hardly any
reason not to use double buffering.  (and if you cannot get pygame
to do fast clear and copy operations, you must be using the wrong
API)





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


Re: passing variable arguments to a function

2005-10-13 Thread Christophe
Ryan Wilcox a écrit :
> Hello all,
> 
> I want to be able to pass a variable number of parameters into a Python
> function. Now, I know how to _receive_ variable arguments, but I don't
> know how to _send_ them.
> 
> def myFunction(*args):
> print args
> 
> myList = [1, 2, 3, 4]
> myFunction(myList)
> 
> this function will print out ([1, 2, 3, 4]).
> 
> Except that's not what I want. I want the equivalent to:
> 
> myFunction(1, 2, 3, 4)
> 
> So, given an array, how can I unpack the array and pass all of the
> elements into a Python function as parameters?
> 
> Thanks in advance!,
> _Ryan Wilcox
> 

myFunction(*myList)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread Paul Rubin
Scott David Daniels <[EMAIL PROTECTED]> writes:
> Current speeds are due to deep pipelines, and a conditional in the
> INCREF code would blow a pipeline.

I think most of the time, branch prediction will prevent the cache
flush.  Anyway, with consed integers, there's still going to be a
conditional or even a dispatch on the tag field.  Finally, when you
know you're dealing with small integers, you don't need to even check
the tags.  Some implementations use the low order bits as tags with a
tag==0 meaning an integer.  That means if you have two tagged integers,
you can add and subtract them without having to twiddle the tags.

The alternative (tag==1 means integer) means you don't have to mask
off the tag bits to dereference pointers, and you can still add a
constant to a tagged int by simply adjusting the constant
appropriately.  E.g., with one tag bit, to increment you'd add 2 to
the tagged int.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Well written open source Python apps

2005-10-13 Thread Michael Ekstrand
On Thursday 13 October 2005 09:43, Ben wrote:
> Could anyone suggest an open source project that has particularly
> well written Python?  I am especially looking for code that people
> would describe as "very Python-ic".  (Not trying to start any kind of
> war - just wanted some good examples of a well written Python app to
> read.)

The Python Standard Library. Thousands of lines of quite good Python 
code. It might not use all the latest features, and there might be a 
few dark corners here and there, but it's still solid. And quite easy 
to understand (I had no difficulty understanding and modifying 
httplib).

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


Re: Well written open source Python apps

2005-10-13 Thread Micah Elliott
On Oct 13, Ben wrote:
> Could anyone suggest an open source project that has particularly well
> written Python?  I am especially looking for code that people would
> describe as "very Python-ic".  (Not trying to start any kind of war -
> just wanted some good examples of a well written Python app to read.)

The Python Package Index (PyPI, or cheeseshop)
 has pointers to a lot of packages that are
likely mostly pythonic.

I don't know if this is spelled out more precisely somewhere, but here
is my notion of a pythonic distribution:

* Has modules grouped into packages, all are cohesive, loosely
  coupled, and reasonable length

* Largely follows PEP  conventions

* Avoids reinventing any wheels by using as many Python-provided modules
  as possible

* Well documented for users (manpages or other) and developers
  (docstrings), yet self-documenting with minimal inline commenting

* Uses distutils for ease of distribution

* Contains standard informational files such as:
  BUGS.txt  COPYING.txt  FAQ.txt  HISTORY.txt  README.txt  THANKS.txt

* Contains standard directory structure such as:
  doc/  tools/ (or scripts/ or bin/)  packageX/  packageY/  test/

* Clean UI, easy to use, probably relying on optparse or getopt

* Has many unit tests that are trivial to run, and code is structured to
  facilitate building of tests

The first example of a pythonic package that comes to my mind is
docutils .

-- 
Micah Elliott
<[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pass a tuple (or list) to a C wrapper function

2005-10-13 Thread Fredrik Lundh
"Java and Swing" wrote:

> anyhow, for receiving an object from python..is it
>
> ok = PyArg_ParseTuple(args, "sO", &x, &y);
>
> ...is it "sO" or "s0" is it O (as in the letter) or 0 (as in the
> number)?  I would think "O" the letter..but it looks like a zero.

eh?  if you're not sure, what keeps you from cutting and pasting ?
or comparing it visually with characters that you type in yourself ?

(it's the letter O, for Object.  the corresponding variable must be a
pointer to a PyObject pointer.  see the documentation for details:

http://www.python.org/doc/current/api/arg-parsing.html

)





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


PyDev 0.9.8.3 released

2005-10-13 Thread Fabio Zadrozny
Hi All,

PyDev - Python IDE (Python Development Enviroment for Eclipse) version 
0.9.8.3 has been released.

Check the homepage (http://pydev.sourceforge.net/) for more details.

Details for Release: 0.9.8.3


Major highlights:


* Debugger was improved to be faster (more info about it at my blog
   --
  http://pydev.blogspot.com/2005/10/high-speed-debugger.html)
* The debugger is now getting info correctly on java classes when
  debugging jython
* Add watch added to the editor popup menu
* Added syntax highlighting to the 'self' token
* Code folding added for 'glued' imports
* Fixed some outline problems


Others that are new and noteworthy:
-

* Debugger does not try to get breakpoints on closed projects anymore
* Some refreshing issues regarding the outline and colors when
  reusing the editor were fixed
* Code completion for relative imports has changed a lot (there were
  some pretty hard-to-find bugs in this area...)
* Some move imports problems fixed
* The auto-add '(self):' now works with tabs too


Cheers,

Fabio

-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
www.esss.com.br

PyDev - Python Development Enviroment for Eclipse
pydev.sf.net
pydev.blogspot.com



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


Re: How to call a script from another?

2005-10-13 Thread Scott David Daniels
Jaime Wyant wrote:
> I think this is the simplest way to do that:
> 
> import sys
> sys.path.append('/path/to/directory/containing/script')
> 
> import zopescript
> zopescript.main()
> 
> The code above assumes:
> o that the path you use to append contains an __init__.py in it...
I don't think this is necessary.  The __init__.py is necessary
if you do something like:
 import sys
 sys.path.append('/path/to/directory/containing')
 from script import zopescript
 zopescript.main()
 # or import zopescript.script; script.zopescript.main()
That is, if the directory ".../containing" needs to be interpreted as
a package.

If the script you want to call is in the same directory as the script
calling it (or any directory on the path), you can simply use:
 import zopescript
 zopescript.main()

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing variable arguments to a function

2005-10-13 Thread Fredrik Lundh
Ryan Wilcox wrote:

> I want to be able to pass a variable number of parameters into a Python
> function. Now, I know how to _receive_ variable arguments, but I don't
> know how to _send_ them.
>
> def myFunction(*args):
> print args
>
> myList = [1, 2, 3, 4]
> myFunction(myList)
>
> this function will print out ([1, 2, 3, 4]).
>
> Except that's not what I want. I want the equivalent to:
>
> myFunction(1, 2, 3, 4)
>
> So, given an array, how can I unpack the array and pass all of the
> elements into a Python function as parameters?

same syntax:

myFunction(*myList)





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


Re: cgi python

2005-10-13 Thread Fredrik Lundh
Paul Boddie wrote:

> Testing Web applications can be hard, but the traceback tells you
> everything you need to know here.

especially if you make sure to use the cgitb module:

http://docs.python.org/lib/module-cgitb.html

while developing/debugging.





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


ImportError: No module named dbm

2005-10-13 Thread mhardas
Hi all,
Iam trying to get 'cvs2svn' to get to work on a Trustix Linux machine.
However is suspect that no dbm is installed because running cvs2svn
gives the following error:

ERROR: your installation of Python does not contain a suitable
DBM module -- cvs2svn cannot continue.
See http://python.org/doc/current/lib/module-anydbm.html to solve.

So I ran test for the dbm installation and got the following,

[EMAIL PROTECTED] /usr/local/lib/python2.3/test# python test_dbm.py
Traceback (most recent call last):
  File "test_dbm.py", line 7, in ?
import dbm
ImportError: No module named dbm

Can you tell me how do I go about getting the dbm module and install
it.??

Thanks again.

Manas.




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


Re: How to call a script from another?

2005-10-13 Thread Christian
Thanks guy's, you have opened  my eyes and made my next step a whole lot 
easier.


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


Technical question on complexity.

2005-10-13 Thread Jerzy Karczmarczuk
Anybody knows where I can find a concrete and guaranteed answer to the following
extremely basic and simple question?

What is the complexity of appending an element at the end of a list?
Concatenating with another?

The point is that I don't know what is the allocation policy... If Python lists
are standard pointer-chained small chunks, then obviously linear. But perhaps
there is some optimisation, after all a tuple uses a contiguous chunk, so it
*might* be possible that a list is essentially equivalent to an array, with its
length stored within, and adding something may be done in constant time (unless
the whole stuff is copied, which again makes the complexity related to the size
of existing structure...)

It is probably possible to retrieve this information from the sources, but I try
first an easier way.
Thank you.

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


wxPython & Cygwin

2005-10-13 Thread Gilles DRIDI
Does someone has installed wxPython on the Cygwin platform, environment ?

Thank you
Gilles DRIDI
http://cdridi.club.fr 


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


Re: Technical question on complexity.

2005-10-13 Thread Fredrik Lundh
Jerzy Karczmarczuk wrote:

> Anybody knows where I can find a concrete and guaranteed answer to the 
> following
> extremely basic and simple question?
>
> What is the complexity of appending an element at the end of a list?

amortized O(1)

> Concatenating with another?

O(n)

> The point is that I don't know what is the allocation policy... If Python 
> lists
> are standard pointer-chained small chunks, then obviously linear. But perhaps
> there is some optimisation, after all a tuple uses a contiguous chunk, so it
> *might* be possible that a list is essentially equivalent to an array, with 
> its
> length stored within, and adding something may be done in constant time

a list consists of a single array of PyObject pointers, plus "allocated" and
"current size" fields.  when you append, allocation is only done when needed,
and the new size is chosen carefully to keep the number of allocations low.
see the source for details (the exact "overallocation" strategy varies some-
what in different Python versions).





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


Re: Let My Terminal Go

2005-10-13 Thread Jorgen Grahn
On Tue, 11 Oct 2005 22:01:23 GMT, Dan Stromberg <[EMAIL PROTECTED]> wrote:
> On Tue, 11 Oct 2005 03:30:23 -0700, Mystilleef wrote:
>
>> Hello,
>> 
>> Thank you. That's all I needed. For some reason, I had always assumed
>> forking was an expensive process. I guess I was ill-informed.
>
> In a loop, yes, it's expensive.

It depends on what you mean by expensive -- web servers can fork for each
HTTP request they get, in real-world scenarios, and get away with it.

> Done once, it's usually not unacceptable.

In fact, I can't think of a scenario where it /would/ be unacceptable ;-)

But back to the original problem: I can't really see why anybody would need
the "let my terminal go" feature. Is there a reason why 'gvim foo.txt&'
isn't good enough?

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Let My Terminal Go

2005-10-13 Thread Paul Rubin
Jorgen Grahn <[EMAIL PROTECTED]> writes:
> It depends on what you mean by expensive -- web servers can fork for each
> HTTP request they get, in real-world scenarios, and get away with it.

This is OS dependent.  Forking on Windows is much more expensive than
forking on Linux.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Perl-Python-a-Day: Sorting

2005-10-13 Thread Marcin 'Qrczak' Kowalczyk
Abdulaziz Ghuloum <[EMAIL PROTECTED]> writes:

> Python FAQs contain an entry to the schwartzian transform.
>
> http://www.python.org/doc/faq/programming.html#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python

This entry is obsolete: it should mention the 'key' option of the
standard sort method.

-- 
   __("< Marcin Kowalczyk
   \__/   [EMAIL PROTECTED]
^^ http://qrnik.knm.org.pl/~qrczak/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Let My Terminal Go

2005-10-13 Thread Grant Edwards
On 2005-10-13, Paul Rubin <> wrote:
> Jorgen Grahn <[EMAIL PROTECTED]> writes:
>> It depends on what you mean by expensive -- web servers can fork for each
>> HTTP request they get, in real-world scenarios, and get away with it.
>
> This is OS dependent.  Forking on Windows is much more
> expensive than forking on Linux.

Under VMS, fork/exec was so expensive that the Bourne shell
implimentation in DECShell executed "simple" commands in the
shell's process rather than do a fork/exec. Shell scripts that
used pipes or similar constructs requiring fork/exec ran _very_
slowly under DECShell.

Since the NT kernel is descended from VMS, I'm not surprised
that a fork is expensive.

-- 
Grant Edwards   grante Yow!  Why are these
  at   athletic shoe salesmen
   visi.comfollowing me??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's garbage collection was Re: Python reliability

2005-10-13 Thread skip

Diez> AFAIK some LISPs do a similar trick to carry int values on
Diez> cons-cells.  And by this tehy reduce integer precision to 28 bit
Diez> or something. Surely _not_ going to pass a regression test suite
Diez> :)

I'm pretty sure this was tried a few years ago w/ Python.  I don't recall
the results, but I'm pretty sure they weren't good enough.  had they been we
could just look at the source.

Folks, most common GC schemes have been tried as experiments over the years.
None have succeeeded, for various reasons.  I think one of the main reasons
is that Python has to "play nice" with external libraries, many of which
weren't written with GC beyond malloc and free in mind.

Here are some pointers interested readers might want to check out:

Tagged integers: 
http://mail.python.org/pipermail/python-dev/2004-July/046139.html

Boehm GC:
http://mail.python.org/pipermail/python-dev/2005-January/051370.html
http://www.python.org/doc/faq/general.html#how-does-python-manage-memory
http://wiki.python.org/moin/CodingProjectIdeas/PythonGarbageCollected

Miscellaneous:
http://mail.python.org/pipermail/python-dev/2002-June/026032.html
http://mail.python.org/pipermail/python-dev/2003-November/040299.html

And lest anyone here think they were the first to suggest getting rid of
reference counting in Python:

http://www.python.org/search/hypermail/python-1993/0554.html

I wouldn't be surprised if there were even earlier suggestions...

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


Re: Let My Terminal Go

2005-10-13 Thread Paul Rubin
Grant Edwards <[EMAIL PROTECTED]> writes:
> Since the NT kernel is descended from VMS, I'm not surprised
> that a fork is expensive.

Apache 2.x supports concurrency via threading as an alternative to
forking, basically in order to get acceptable performance on Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list


form filling XML

2005-10-13 Thread George
How can I do the following in python:

given two strings:
form="""

  My Sample Web Page  


What are the weekdays?

Monday
Tuesday
Wednesday
Thursday
Friday




"""
fillin="""

maandag
dinsdag
woensdag
donderdag
vrijdag
zaterdag
zondag

"""

How can I compare the text in the element tags  with the elements
tags in filling and if they match replace the text within the elements
tags  with the text in the matching element tag of fillin.
For example Since the text Monday in form matches the Element tag
 in fillin put maandag in the element tag  of Monday.

Kind of a Pseudo Code

import xml.dom.minidom

def xmlform(form=None, fillin=None):
 Fo = xml.dom.minidom.parseString(form)
 Fi = xml.dom.minidom.parseString(fillin)

 Fo information:
 get element tags for li
 get text for li

 Fi information:
 get childtags for dutchdays

 if(text for li=child tags for dutchdays):
   replace child tags for dutchdays text with text for li

There needs to be a loop but I cannot figure out what type of loop
maybe a while len(Fo)>0: to process through the form.

Thanks for the help!!

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


Re: ImportError: No module named dbm

2005-10-13 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Can you tell me how do I go about getting the dbm module and install
> it.??

http://www.google.com/search?q=trustix+python+dbm





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


Re: Let My Terminal Go

2005-10-13 Thread Fredrik Lundh
Jorgen Grahn wrote:

> > Done once, it's usually not unacceptable.
>
> In fact, I can't think of a scenario where it /would/ be unacceptable ;-)

if you're stuck on a system that doesn't use copy-on-write ?





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


Forcing a stack trace from the command line?

2005-10-13 Thread Willie Walker
Hi:

I'm working on Orca, a screen reader for the GNOME platform,
and it's being done in Python.  Python is working really for
us right now and I'm quite happy with many aspects of it.

Is there a function like CTRL-Backspace in Python?  There is
a hang in my code somewhere and I'm unable to find it.  When
the hang occurs, all "print" commands seem to stop and I can
only recover by killing the app via Ctrl-Z and kill.  In these
cases, Ctrl-C doesn't work even though I've registered signal
handlers:

   signal.signal(signal.SIGINT, shutdownAndExit)
   signal.signal(signal.SIGQUIT, shutdownAndExit)

What I'd really like to be able to do is to use something like
Java's CTRL-Backspace to dump a stack trace in these instances
just to give me a clue about where my code is during the hang.

I've tried using sys.settrace() to track things, but it seems
to introduce something into the system that prevents me from
being able to reproduce the hang.

Any advice would be greatly appreciated.

Thanks!

Will

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


Re: form filling XML

2005-10-13 Thread Fredrik Lundh
"George" <[EMAIL PROTECTED]> wrote:

> How can I compare the text in the element tags  with the elements
> tags in filling and if they match replace the text within the elements
> tags  with the text in the matching element tag of fillin.
> For example Since the text Monday in form matches the Element tag
>  in fillin put maandag in the element tag  of Monday.

here's one way to do it:

import elementtree.ElementTree as ET
# or: import cElementTree as ET
# or: import lxml.etree import ET

form="""..."""

fillin="""..."""

form_elem = ET.XML(form)
fill_elem = ET.XML(fillin)

for elem in form_elem.findall(".//li"):
text = fill_elem.findtext(elem.text)
if text:
elem.text = text

print ET.tostring(form_elem)

using your example, this prints:


  My Sample Web Page  


What are the weekdays?

maandag
dinsdag
woensdag
donderdag
vrijdag





links:

http://effbot.org/zone/element-index.htm
http://effbot.org/zone/celementtree.htm
http://codespeak.net/lxml/

(if you're on linux, check your local package source for elementtree
packages)





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


1-liner to iterate over infinite sequence of integers?

2005-10-13 Thread Neal Becker
I can do this with a generator:

def integers():
x = 1
while (True):
yield x
x += 1

for i in integers(): 

Is there a more elegant/concise way?

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


Re: installer for amd64 build of python?

2005-10-13 Thread Brett Hoerner
As an aside to this, are there any freely available C compilers for
Windows that can compile 64-bit binaries?  I find nothing for Cygwin or
MinGW...

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


Re: installer for amd64 build of python?

2005-10-13 Thread Trent Mick
[Brett Hoerner wrote]
> As an aside to this, are there any freely available C compilers for
> Windows that can compile 64-bit binaries?  I find nothing for Cygwin or
> MinGW...

Yes. The MS Platform SDK is free and includes a compiler that can target
x86, ia64 and x64 (the latter is what MS -- and Sun -- are calling
AMD64).

Trent

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


Re: 1-liner to iterate over infinite sequence of integers?

2005-10-13 Thread Will McGugan
Neal Becker wrote:
> I can do this with a generator:
> 
> def integers():
> x = 1
> while (True):
> yield x
> x += 1
> 
> for i in integers(): 
> 
> Is there a more elegant/concise way?
> 

import itertools
for i in itertools.count():
print i


Will McGugan
-- 
http://www.willmcgugan.com
"".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in 
"jvyy*jvyyzpthtna^pbz")
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >