Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Peter Otten
snacktime wrote:

> I need to convert a generator expression to a list expression so it
> will work under python 2.3.
> 
> I rewrote this:
> 
> for c in range(128):
>   even_odd = (sum(bool(c & 1< 
> As this:
> 
> for c in range(128):
>   bo = [bool(c & 1<   even_odd = sum(bo) & 1
> 
> 
> Seems to work, is there a better way to do this?

Summing over zeros seems pointless, so

>>> for c in range(128):
... print len([1 for b in range(8) if c & 1 << b]) & 1,
...
0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1
1 0 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0
1 0 0 1 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0
0 1 0 1 1 0 0 1 1 0 1 0 0 1

The same simplification works for genexps, but you have to use sum() there
instead of len(). Another optimization would be to precalculate the
bitmasks [1 << b for b in range(8)] outside the loop.

Peter

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


Re: [Fwd: Re: [Uuu-devel] languages] <-- Why Python

2005-02-21 Thread Ville Vainio
> "Mike" == Mike Meyer <[EMAIL PROTECTED]> writes:

Mike> IPython's pysh seems a little clumsy for interactive use, as
Mike> it requires special characters to distinguish between
Mike> commands to be passed to the shell and commands to be passed
Mike> to the scripting language. This should be contrasted with

What do you mean by "the commands to be passed to the shell"? Commands
on the path (the normal situation in Unix) can be executed directly
just like in bash et al. Ditto for "magic" functions if "automagic" is
on.

I only use ! for calling commands that are in the current directory. A
*real* deficiency with ipython/pysh under Linux is the lack of job
control (in the sense that ^z suspends the whole ipython). I don't see
why pysh would not be able to match and exceed the capabilities of
shell in job control as well. It's not a priority for fperez himself
ATM, but we'll see how easy it is to add shellish job control in the
future after the refactoring...

Mike> I'll say it again - if you're arguing about which language
Mike> to use, you're arguing about the wrong thing.

In a sense C is the native language of Unix and Windows (system calls
are in C). It might make sense to expose the OS as Python objects.

I work w/ Symbian OS in my day job, with the OS API in C++. I'm not
sure whether it's a good idea or not, but at least some people are
doing it :).

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Fwd: Re: [Uuu-devel] languages] <-- Why Python

2005-02-21 Thread Ville Vainio
> "Mike" == Mike Meyer <[EMAIL PROTECTED]> writes:

Mike> I've actually done some work on using CORBA as a COM for
Mike> Unix (or, as I think of it, an ARexx for Unix). After being
Mike> exposed to Plan 9, I've decided that's a better
Mike> solution. CORBA has the advantage that you can work on it
Mike> without getting buy-in from kernel vendors.

The problem w/ CORBA is the alleged lack of speed. ISTR there was lots
of controversy w/ the way Gnome used CORBA (Bonobo) and how it was too
slow for Desktop apps. I don't know what the current status is - CORBA
has always seemed more than fast enough for me.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test for structure

2005-02-21 Thread Martin Miller
Yes, both string and lists have a __getitem__ attribute:

>>> c1 = 'abc'
>>> c2 = ['de', 'fgh', 'ijkl']
>>> hasattr(c1, '__getitem__')
True
>>> hasattr(c2, '__getitem__')
True

In other words you could index elements of either one using [].

Likewise, both a string and list would produce a usable iterator using
the following logic:

try:
itr = iter(a)
except TypeError:
# 'a' is not iterable
else:
# 'a' is iterable

In either case, you can't tell a string and list apart, which is what
the OP wanted to know, namely how to differentiate the two. EAPF is
fine, but what operation would answer the string vs list question?

Perhaps the test for an __iter__ attribute *is* the way to go because
you can tell the difference between the two type. Again I don't know
because the OP doesn't give enough information. I suspect, but don't
know, that it could be so that either one string or a list of strings
as an argument could treated as a list of 0 or more strings and
accessed by indices by most of the rest of the code.

I think the technique suggested by Robin Munn nearly a year ago (and
referenced by the link in Simon Brunning's post):
http://groups-beta.google.com/group/comp.lang.python/msg/c8befd4bed517bbc
namely:

try:
a + ''
except TypeError:
pass
else:
a= [a]

would be a good usable solution, although it's not totally infallible.
It may not be possible to give a better answer without more real
information about the desired usage.

Martin


=
Steven Bethard wrote:
> Terry Hancock wrote:
>  > But you probably shouldn't do that. You should probably just test
to
>  > see if the object is iterable --- does it have an __iter__ method?
>  >
>  > Which might look like this:
>  >
>  > if hasattr(a, '__iter__'):
>  > print "'a' quacks like a duck"
>
> Martin Miller top-posted:
> > I don't believe you can use the test for a __iter__ attribute in
this
> > case, for the following reason:
> >
> c1 = 'abc'
> c2 = ['de', 'fgh', 'ijkl']
> hasattr(c1, '__iter__')
> > False
> >
> hasattr(c2, '__iter__')
> > True
>
> Right.  str and unicode objects support iteration through the old
> __getitem__ protocol, not the __iter__ protocol.  If you want to use
> something as an iterable, just use it and catch the exception:
>
> try:
>  itr = iter(a)
> except TypeError:
>  # 'a' is not iterable
> else:
>  # 'a' is iterable
>
> Another lesson in why EAPF is often better than LBYL in Python[1].
> 
> STeVe
> 
> [1] http://www.python.org/moin/PythonGlossary

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


Re: Moving to Python from PHP - 3 questions

2005-02-21 Thread Fredrik Lundh
Joe Francia wrote:

> You'll also want to probably look at some of the templating kits, of which 
> Cheetah and/or 
> ElementTree work best for me.  (Well, ElementTree isn't exactly a templating 
> kit - it's a 
> general-purpose XML tookit - but it is easily used for templating.)

if you want element-based templating, see:

http://lesscode.org/projects/kid/

 



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


[PyGTK] forbid focus of TreeView columns

2005-02-21 Thread Franck Pommereau
Hi all,
I'm building a PyGTK interface in which I would like that no widget 
would be able to get the focus (and so to be activated by pressing the 
Return key). For this purpose, for each widget, I do:

widget.set_property("can-focus", gtk.FALSE)
My problem is a TreeView which has a clickable column, it get the 
default focus and I did not find how to forbid that.

I tried:
def focus (widget, *args) :
try :
widget.set_property("can-focus", gtk.FALSE)
except :
pass
try :
widget.set_property("can-default", gtk.FALSE)
except :
pass
win.forall(focus)
where win is my application window (I also tried on the TreeView) but it 
doesn't work.  :-(
I also tried with widget.unset_flags, same result.  :-((

If I choose another widget and give it the default focus 
(widget.grab_default and widget.grab_focus) it's OK until I click on the 
column which then keeps the focus.  :-(((

I'm sure I could capture the Return key but I don't want to have this 
dashed line around the focused widget...

I think that this column has somewhere an associated widget but I could 
not find it anywhere (and neither could win.forall).

I'm using PyGTK-2.0.0 and cannot use another version.
Thanks in advance for any idea!
Franck
--
http://mail.python.org/mailman/listinfo/python-list


[PyGTK] Resizing a HandleBox

2005-02-21 Thread Franck Pommereau
Hi all,
I'm using PyGTK-2.0.0, when I detach a HandleBox, the resizing of the 
newly created window is broken: it can be resized but it's content (the 
HandleBox and its child) is not affected at all and is not resized.

Does any one have a solytion to this problem?
Thanks in advance!
Franck
--
http://mail.python.org/mailman/listinfo/python-list


Re: [PyGTK] Resizing a HandleBox

2005-02-21 Thread Robert Kern
Franck Pommereau wrote:
Hi all,
I'm using PyGTK-2.0.0, when I detach a HandleBox, the resizing of the 
newly created window is broken: it can be resized but it's content (the 
HandleBox and its child) is not affected at all and is not resized.

Does any one have a solytion to this problem?
I'm afraid I don't, but I'll bet that someone on the PyGTK mailing list 
does.

http://www.daa.com.au/mailman/listinfo/pygtk
--
Robert Kern
[EMAIL PROTECTED]
"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to Python from PHP - 3 questions

2005-02-21 Thread bruno modulix
Michal Migurski wrote:
The python-based zope application server has session management. Togther
with a built-in user and access rights management.
...
This can be done in zope if you name a variable :list. That then 
will
give you the variable as list regardless of the number of occurences.

Thank you. My impression of Zope in the past has been that it does what 
I need, along with 10,000 other things I don't (built in WebDAV 
server?!),
Our web designer just *loves* it (and ZopePageTemplates too, since they 
work quite ok with it's favorite html editor...). Might not be useful to 
you, but...

but clearly I owe it another chance. I've been initially 
attracted to mod_python because of its raw simplicity and its apparent 
similarity to mod_php and mod_perl, which I am familiar with. I'll give 
Zope a try.
Zope is a great product, but hard to get into, and it's sometime just 
too big and fat for some simple things. So while it may be worth giving 
it a try, I would not recommend it for all and any project.

Now when it comes to session management and the like, there are many 
other libs/frameworks/etc based on mod_python.

This might be a good start :
http://www.python.org/topics/web/
HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for 
p in '[EMAIL PROTECTED]'.split('@')])"
--
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread bruno modulix
Ilias Lazaridis wrote:
Bruno Desthuilliers wrote:
[...]
closing thread
http://groups-beta.google.com/group/comp.lang.python/msg/f2ae9cdbe16676d1
Nope. You are not entitled to close thread. This is irrelevant.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for 
p in '[EMAIL PROTECTED]'.split('@')])"
--
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread bruno modulix
Ilias Lazaridis wrote:
Should a professional developer take python serious?
A *professionnal developper*, yes. But this is irrelevant to you.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for 
p in '[EMAIL PROTECTED]'.split('@')])"
--
http://mail.python.org/mailman/listinfo/python-list


IDLE output too slow for practical use after upgrade from P2.2.2 to P2.4

2005-02-21 Thread Anthra Norell



Hi,
   I upgraded from 2.2.2 to 2.4 and all 
is well except the output to the IDLE window is now twenty times slower than it 
was before, making the window utterly unusable for verbose output. The statement 
-- for i in range (100): print i -- now takes about forty-five seconds to complete! Used to be 
two.
Python 2.4 on Windows ME.
Hints will be gratefully received by 
Frederic
 
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Don't understand global variables between modules

2005-02-21 Thread Bart
Hi all

I don't understand globals between multiple modules in a python program. I
really don't. I've narrowed it down to the following two very simple
programs a.py and b.py. When I run a.py I get the following output:

inc:  2
A:  2
inc:  3
B:  3
C:  1
I don't understand the last line at all. Why is my x variable 1 after having
been incremented twice? Is there more than one global space? Is this
backreference to the original a.py not allowed?

I could use some help.

Thanks

Bart van Deenen



a.py:
-
import b
x=1

def inc():
global x
x+=1
print "inc: ",x

if __name__=="__main__":
b.test()
print "C: ",x

b.py:
-
def test():
import a
a.inc()
print "A: ",a.x
a.inc()
print "B: ",a.x

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


Re: Moving to Python from PHP - 3 questions

2005-02-21 Thread grahamd

Michal Migurski wrote:
> 3) Structured request variables. PHP has a really handy feature where

> request variables with name like "foo[]", "foo[bar]", or
> "foo[bar][baz]" are automatically structured into nested associative
> arrays. I can see that the python cgi module will make a list of
> MiniFieldStorage objects when more than one variable with the same
name

Someone already piped in by suggesting Vampire for mod_python, so
would add that Vampire supports structured form variables by making
use of:

  http://svn.colorstudy.com/trunk/Validator/validator/variabledecode.py

Thus, if you follow the form naming conventions this code supports,
then data can be turned into lists and dictionaries as appropriate. The
only thing is the naming convention is different to what you list
above.
Read the comments in linked code to see what it does actually use.

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


MDaemon Warning - virus found: Returned mail: see transcript for details

2005-02-21 Thread Post Office

*** WARNING **
Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado 
un fichero anexo(s) infectado(s).  Por favor revise el reporte de abajo.

AttachmentVirus name   Action taken
--
document.zip  Email-Worm.Win32.Mydoom.m Removed


**


The original message was received at Mon, 21 Feb 2005 11:45:14 +0100
from 186.110.134.53

- The following addresses had permanent fatal errors -


- Transcript of session follows -
... while talking to 31.13.99.160:
>>> MAIL FROM:"Post Office" <[EMAIL PROTECTED]>
<<< 502 "Post Office" <[EMAIL PROTECTED]>... Denied

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

Re: Don't understand global variables between modules

2005-02-21 Thread Fredrik Lundh
Bart wrote:

> I don't understand globals between multiple modules in a python program. I
> really don't. I've narrowed it down to the following two very simple
> programs a.py and b.py. When I run a.py I get the following output:
>
> inc:  2
> A:  2
> inc:  3
> B:  3
> C:  1
>
> I don't understand the last line at all. Why is my x variable 1 after having
> been incremented twice?

because running a script isn't the same thing as importing it.  try adding
"print __name__" lines before your other print statements so you can see
who's printing what.

> Is there more than one global space?

in this case, there are more module namespaces than you think.

this page might help (especially the "Using Modules as Scripts" section):

http://effbot.org/zone/import-confusion.htm

 



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


Re: Moving to Python from PHP - 3 questions

2005-02-21 Thread grahamd
> If you do manage to get mod_python working, I suggest taking a look
at
> Vampire as well: http://www.dscpl.com.au/projects/vampire/
> I have had good experience with it. Once you start using mod_python
> you'll realize you can really go anywhere you want; and that's not
> necessarily a good thing. Vampire points you in a nice direction (I
> don't want to say 'the right' direction).

Vampire is still in a growing phase, so would be interested to hear any
comments you may have about how it can be improved. Up until now
I have mainly been focusing on making the basic features of mod_python
just that bit easier to use.

And yes I know that a lot more documentation would be a good start.
I am so snowed under with work in my real job at the moment that
progress is slow in that respect. :-(

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


Re: unicode encoding usablilty problem

2005-02-21 Thread Fredrik Lundh
"aurora" <[EMAIL PROTECTED]> wrote:

>> if you don't know what a and b comes from, how can you be sure that
>> your program works at all?  how can you be sure they're both strings?
>
> a and b are both string.

how do you know that?

>> if you have unit tests, why don't they include Unicode tests?
>
> How do I structure the test cases to guarantee coverage? It is not  practical 
> to test every 
> combinations of unicode/8-bit strings. Adding  non-ascii characters to test 
> data probably make 
> problem pop up earlier. But it is arduous

sounds like you don't want to test for it.  sorry, cannot help.  I prefer
to design libraries so they can be tested, and design tests so they test all
important aspects of my libraries.  if you prefer another approach, there's
not much I can do, other than repeating what I said at the start: if you do
things the right way (decode on the way in, encode on the way out), it
just works.

 



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


Re: lambda closure question

2005-02-21 Thread Carl Banks
Mike Meyer wrote:
> "Carl Banks" <[EMAIL PROTECTED]> writes:
>
> > Say you have a suite of functions, all of which are called by some
main
> > function and each other, and all of which need to access a lot of
the
> > same data.  The best, most straightforward way to do it is to have
the
> > common data be a local variable of the main function, and nest the
> > suite inside it.  The other way to do it, passing around a common
data
> > structure, add complexity and hurts performance.
>
> The third way to do it is to make the thing a class.

Which is kind of the same thing as passing a structure around, only
with a somewhat more convenient syntax.  But yes.


> Make all the
> functions methods of the class, and all the data instance
> variables. You may well want to make the main function the __call__
> method of the class. In an OO environment, this may be a better, more
> straightforward way than nesting fnctions.

There are good reasons for sometimes using a class, but
straightforwardness is, IMHO, not one of them.

You're writing a function (in the abstract sense: you are creating an
entity that you call with input to get output, and that has local
storage that doesn't need to exist afterwards).  Is it more
straightforward to implement an (abstract) function with a function
object (i.e., the object that was designed exactly for that purpose),
or with a class (designed for a different purpose: to create new
types)?  I'd definitely go with the former.  Implementing an (abstract)
function as a class obscures its purpose.

I agree that there are many times when a class is a more appropriate
implementation of an (abstract) function, such as if your suite of
subfunctions has to rebind common variables, or if your (abstract)
function has so many return values it's better to define it as a class
and have the caller refer to the attributes.  However, I'd say this
comes at the expense of straightforwardness (or, rather, it exchanges
one sort of striaghtforwardness for another sort judged more
important).


As for implementing an (abstract) function as a class just because
you're in an OO environment: that's just thinking backwards.

"OOP is the shizzle so I'm going to implement everything as a class,"
is simply the wrong way to think.  There's a reason OOP is the shizzle:
because it's very often a good representation of the problem.  But it
isn't always.  And when it isn't,  and when a better way exists (as in
this case), you should use the better way, even in the highly OO
environment.  OOP is a means, not an end.


-- 
CARL BANKS

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


Keyword Named Args

2005-02-21 Thread Fuzzyman
A colleague and I have built a Validator object for use with ConfigObj
and other general schema situations. A config file is used to store a
schema that specifies how to test a value that it is valid.

keyword=function(param1, param2)

e.g. you could specify :
size = range(30, 50)

This means that the keyword 'size' must be an integer between 30 and
50. There is a matching function stored in a dictionary that is called
and the relevant arguments passed to it.

The function name and parameters are parsed from the config file that
defines the schema.

args, fname = parsefunction('range(30,50)')
test = funcdict[fname](*args)

What I can't easily see is any way of passing named keyword arguments
to the function. Suppose we wanted to pass keyword=param to a function
- is there any way of doing this ... obviously passing in
'keyword=param' as text has entirely the wrong result..

Anyone got any clues ? I suspect compiling the function into a code
object will help but this is a slightly black art for me.

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: lambda closure question

2005-02-21 Thread Carl Banks

jfj wrote:
> The costly extra feature is this:
> ###
>   def foo():
>  def f():
> print x
>  x=1
>  f()
>  x=2
>  f()
>  return f
> foo()()
> #
> which prints '1 2 2'
>
> The fractal code runs a little _slower_ because of this ability.
> Although the specific program does not take advantage of it!

True, in this case.  (Although it's not that much slower; I think it's
only one extra dereference per access plus a little overhead.)  But try
to extend your mind a bit and imagine that the recursive nested
function is called as part of a larger routine.  Say, for example,
something that seeks a certain shape for the fractal.

. def ifs(transformations,maxdepth):
. def add_point(...):
. ...
. def test_shape():
. ...
. while True:
. add_point(0,0,0,0)
. x = test_shape()
. if x < THRESHOLD:
. break
. transformations = adjust(transformation)

transformations gets rebound, so you'd need a reference to it.

I realize that this is getting more and more situationally specific (I
wouldn't yet say contrived, though; I have referenced changing bindings
a few times).  Maybe you have a point.


-- 
CARL BANKS

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


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Dan Sommers
On Sun, 20 Feb 2005 20:56:52 -0800,
snacktime <[EMAIL PROTECTED]> wrote:

> I need to convert a generator expression to a list expression so it
> will work under python 2.3.

> I rewrote this:

> for c in range(128):
>   even_odd = (sum(bool(c & 1< As this:

> for c in range(128):
>   bo = [bool(c & 1<   even_odd = sum(bo) & 1


> Seems to work, is there a better way to do this?

for c in range( 128 ):
even_odd = 0
print '%3d' % c,
while c:
c &= c - 1
even_odd = not even_odd
print int( even_odd )

Okay, so your inner loop is only counting to 8, but IMO this is a good
example of how to use a better algorithm instead of optimizing the code
of a naÃve one.  My inner loop only iterates over 1-bits.

"Better," of course is all relative.  Your algorithm obviously counts
bits in an integer.  My algorithm is less clear at first glance (and
even second and third glance), but nearly idiomatic to those of us who
spent lots of time writing embedded assembly code.

If you have the space to spare, a lookup table (pre-calculated or
created during your program's initialization) is probably the best way
to go.

Regards,
Dan

-- 
Dan Sommers

Never play leapfrog with a unicorn.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: combining several lambda equations

2005-02-21 Thread Antoon Pardon
Op 2005-02-18, Steven Bethard schreef <[EMAIL PROTECTED]>:
> Paddy McCarthy wrote:
>> x=lambda : A < B
>> y=lambda : C+6 >= 7
>>
> [snip]
>>
>> Z=lambda : (A=7)
>
> See "Inappropriate use of Lambda" in
> http://www.python.org/moin/DubiousPython
>
> Perhaps your real example is different, but notice that
>   = lambda : 
> is equivalent to
>  def ():
>  return 
> except that the latter will give your function a useful name.  No reason 
> to use the *anonymous* function construct to create a *named* function.

So and if I have code like this:

f = lamda x:x 
for g in some_iter:
  f = compose(g,f)


Do you still think that one should use a named function in this case?

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


Re: Keyword Named Args

2005-02-21 Thread Diez B. Roggisch
> What I can't easily see is any way of passing named keyword arguments
> to the function. Suppose we wanted to pass keyword=param to a function
> - is there any way of doing this ... obviously passing in
> 'keyword=param' as text has entirely the wrong result..

Im not sure if I understand you fully, but if what you are after is how to
pass named parameters analog to positional args, do it as dict:

def foo(name=None):
print name

foo(**{name: "Fuzzy"})


-- 
Regards,

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


functions and named keyword arguments

2005-02-21 Thread Fuzzyman
Sorry if this is a duplicate - I use the google interface and sometiems
it screws up (not showing stuff you've posted *or* not posting it).
Before you ask it's because at work I have no NNTP and *heavily*
restricted http.

A colleague and I have built a Validator object for use with ConfigObj
and other general schema situations. A config file is used to store a
schema that specifies how to test a value that it is valid.

keyword=function(param1, param2)

e.g. you could specify :
size = range(30, 50)

This means that the keyword 'size' must be an integer between 30 and
50. There is a matching function stored in a dictionary that is called
and the relavant arguments passed to it.

The function name and parameters are parsed from the config file that
defines the schema.

args, fname = parsefunction('range(30,50)')
test = funcdict[fname](*args)

What I can't easily see is any way of passing named keyword arguments
to the function. Suppose we wanted to pass keyword=param to a function
- is there any way of doing this ... obviously passing in
'keyword=param' as text has entirely the wrong result..

Anyone got any clues ? I suspect compiling the function into a code
object will help but this is a slightly black art for me.

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: gui scripting

2005-02-21 Thread Simon Brunning
On 17 Feb 2005 04:48:19 -0800, Tonino <[EMAIL PROTECTED]> wrote:
> thanks - am already involved in a process to modify winguiauto.py  -
> this is a GREAT start but we need more control and better handleing ;)

Can you be more specific?

> Thanks for the WATSUP site - will check on this as well ;)

WATSUP uses winguiauto.py.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda closure question

2005-02-21 Thread Antoon Pardon
Op 2005-02-19, jfj schreef <[EMAIL PROTECTED]>:
> Carl Banks wrote:
>> Ted Lilley wrote:
>> 
>> 
>>>Unfortunately, it doesn't work.  It seems the closure keeps track of
>>>the variable fed to it dynamically - if the variable changes after
>>  [...]
>>>
>>>At least, that's the explanation I'm deducing from this behavior.
>> 
>> 
>> And that's the correct explanation, chief.
>
>> 
>> It is intended that way.  As an example of why that is: consider a
>> nested function called "printvars()" that you could insert in various
>> places within a function to print out the value of some local variable.
>>  If you did that, you wouldn't want printvars to print the values at
>> the time it was bound, would you?
>
> Allow me to disagree (and start a new "confused with closures" thread:)
>
> We know that python does not have references to variables. To some
> newcomers this may seem annoying but eventually they understand the
> pythonic way and they do without them. But in the case of closures
> python supports references!
>
> Nested functions, seem to do two independent things:
>1) reference variables of an outer local scoope
>2) are functions bound dynamically to constants
>
> These two are independent because in:
> ##
> def foo():
>  def nested():
>   print x
>  f = nested
>  x = 'sassad'
>  f()
>  x = 'aafdss'
>  f()
>  return f
> ##
>
> once foo() returns there is no way to modify 'x'!
> It becomes a kind of constant.

In this particular case yes. But not in general, what about
this:

>>> def F():
...   l = []
...   def pop():
... return l.pop()
...   def push(e):
... l.append(e)
...   return pop, push
... 
>>> pop, push = F()
>>> push(1)
>>> pop()
1
>>> push(2)
>>> push(3)
>>> pop()
3
>>> pop()
2

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


Re: functions and named keyword arguments

2005-02-21 Thread Diez B. Roggisch
> Sorry if this is a duplicate - I use the google interface and sometiems
> it screws up (not showing stuff you've posted *or* not posting it).
> Before you ask it's because at work I have no NNTP and *heavily*
> restricted http.

It is - so I requote my answer :)


Im not sure if I understand you fully, but if what you are after is how to
pass named parameters analog to positional args, do it as dict:

def foo(name=None):
print name

foo(**{name: "Fuzzy"})

-- 
Regards,

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


Re: How Do I get Know What Attributes/Functions In A Class?

2005-02-21 Thread Kent Johnson
Hans Nowak wrote:
[EMAIL PROTECTED] wrote:
Hi,
I'm new to python.  Given a class, how can I get know what
attributes/functins in it without dig into the source?

Use the dir function:
 >>> from smtplib import SMTP
 >>> dir(SMTP)
['__doc__', '__init__', '__module__', 'close', 'connect', 'data', 
'debuglevel', 'docmd', 'does_esmtp', 'ehlo', 'ehlo_resp', 'expn', 
'file', 'getreply', 'has_extn', 'helo', 'helo_resp', 'help', 'login', 
'mail', 'noop', 'putcmd', 'quit', 'rcpt', 'rset', 'send', 'sendmail', 
'set_debuglevel', 'starttls', 'verify', 'vrfy']

To get more detailed information than just a list of names, see the 
inspect module.
Or use 'help' (which is build on top of inspect):
 >>> from smtplib import SMTP
 >>> help(SMTP)
Help on class SMTP in module smtplib:
class SMTP
 |  This class manages a connection to an SMTP or ESMTP server.
 |  SMTP Objects:
 |  SMTP objects have the following attributes:
 |  helo_resp
 |  This is the message given by the server in response to the
 |  most recent HELO command.
etc.
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: intersection of 2 list of pairs

2005-02-21 Thread Pierre Quentel
Another method is to build two sets of sets, one for E1 and one for E2, 
then make the intersection of these sets

- with Python 2.3
>>> E1=[('a','g'),('r','s')]
>>> E2=[('g','a'),('r','q'),('f','h')]
>>> from sets import Set,ImmutableSet
>>> f=Set([ImmutableSet(s) for s in E1])& Set([ImmutableSet(s) for s in 
E2])
>>> [tuple(x) for x in f]
[('a', 'g')]

- with Python 2.4
>>> E1=[('a','g'),('r','s')]
>>> E2=[('g','a'),('r','q'),('f','h')]
>>> f=set([frozenset(s) for s in E1]) & set([frozenset(s) for s in E2])
>>> [tuple(x) for x in f]
[('a', 'g')]
You must use ImmutableSet or frozenset to be able to create a set of sets
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Re: lambda closure question

2005-02-21 Thread jfj
Antoon Pardon wrote:
Op 2005-02-19, jfj schreef <[EMAIL PROTECTED]>:
once foo() returns there is no way to modify 'x'!
It becomes a kind of constant.

In this particular case yes. But not in general, what about
this:

def F():
...   l = []
...   def pop():
... return l.pop()
...   def push(e):
... l.append(e)
...   return pop, push
... 

Others will point this out, but if I'm fast enough...
This does not change the object referenced by l.
It calls methods of it and because it is mutable the containts
of the list are modified.
'l' is a list at address, 0x and that can never change once
F() has returned.
jfj
--
http://mail.python.org/mailman/listinfo/python-list


Re: recommended way of generating HTML from Python

2005-02-21 Thread Kent Johnson
Michele Simionato wrote:
The problem is a problem of standardization, indeed. There plenty of
recipes to
do the same job, I just would like to use a blessed one (I am teaching
a Python
course and I do not know what to recommend to my students).
Why not teach your students to use a template system?
FWIW, here is a my version of the recipe (stripped down to the bare
essentials)
.def makeattr(dict_or_list_of_pairs):
.dic = dict(dict_or_list_of_pairs)
.return " ".join("%s=%r" % (k, dic[k]) for k in dic)
.class HTMLTag(object):
.def __getattr__(self, name):
.def tag(value, **attr):
."""value can be a string or a sequence of strings."""
.if hasattr(value, "__iter__"): # is iterable
.value = " ".join(value)
.return "<%s %s>%s\n" % (name, makeattr(attr), value,
name)
.return tag
# example:
.html = HTMLTag()
.tableheader = ["field1", "field2"]
.tablebody = [["a1", "a2"],
. ["b1", "b2"]]
.html_header = [html.tr(html.th(el) for el in tableheader)]
.html_table = [html.tr(html.td(el) for el in row) for row in tablebody]
.print html.table(html_header + html_table)
*Shudder*
I've written web pages this way (using a pretty nice Java HTML generation package) and I don't 
recommend it. In my experience, this approach has several drawbacks:
- as soon as the web page gets at all complex, the conceptual shift from HTML to code and back is 
difficult.
- It is hard to work with a designer. The designer will give you sample web pages which then have to 
be hand-translated to code. Changes to the web page have to be located in the code.
- There is no separation of content and presentation

IMO templating systems are a much better solution. They let you express HTML in HTML directly; you 
communicate with a designer in a language the designer understands; you can separate content and 
presentation.

Kent

  Michele Simionato

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


Re: lambda closure question

2005-02-21 Thread Antoon Pardon
Op 2005-02-21, jfj schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>> Op 2005-02-19, jfj schreef <[EMAIL PROTECTED]>:
>> 
>>>once foo() returns there is no way to modify 'x'!
>>>It becomes a kind of constant.
>> 
>> 
>> In this particular case yes. But not in general, what about
>> this:
>> 
>> 
>def F():
>> 
>> ...   l = []
>> ...   def pop():
>> ... return l.pop()
>> ...   def push(e):
>> ... l.append(e)
>> ...   return pop, push
>> ... 
>> 
>
> Others will point this out, but if I'm fast enough...
>
> This does not change the object referenced by l.
> It calls methods of it and because it is mutable the containts
> of the list are modified.
> 'l' is a list at address, 0x and that can never change once
> F() has returned.

I'm sorry but in my understanding of english mutating an object
is changing or modifying it. Yes it is stil the same list but
that list was not unmodified.

But I'll get back at what seems you actually wanted to say:
That there is no way to rebind 'x' or in my case 'l' and
with that I have to agree although I personnaly find that
a lack in python

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


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread JanC
Nick Vargish schreef:

> Please consider a visit to
> tinyurl.com before posting a monster like that... :^)

As long as he also posts the full URL...

-- 
JanC

"Be strict when sending and tolerant when receiving."
RFC 1958 - Architectural Principles of the Internet - section 3.9
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda closure question

2005-02-21 Thread Diez B. Roggisch
> But I'll get back at what seems you actually wanted to say:
> That there is no way to rebind 'x' or in my case 'l' and
> with that I have to agree although I personnaly find that
> a lack in python

It's not only that way in python, but in java too. So it seems that there is
a fundamental principle behind it: In a language that allows sideeffects,
these will actually happen.

If you're after side-effect free programming, I recommend using a functional
programming language like ocaml or haskell. In these, you can't mutate
objects at all, only recreate them and rebind them to new variables. This
prevents whole classes of errors - but of course it also introduces all
kinds of other constraints on your programming style, e.g. using monads and
so on.

-- 
Regards,

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


Re: lambda closure question

2005-02-21 Thread Duncan Booth
Antoon Pardon wrote:

> But I'll get back at what seems you actually wanted to say:
> That there is no way to rebind 'x' or in my case 'l' and
> with that I have to agree although I personnaly find that
> a lack in python

'no way' is a bit strong. You can use hacks such as the one I posted a 
couple of weeks back:

>>> import hack
>>> def F():
l = 'hello there'
def get():
return l
return hack.mksetter(lambda: l), get

>>> set, get = F()
>>> get()
'hello there'
>>> set('testing')
'testing'
>>> get()
'testing'

'no official, supported, or portable way' would be more accurate.

I've never actually felt the need to set variables from inside a nested 
function, and I wouldn't use a hack like this in production code unless 
there was a *very* good reason for it, but since I figured out how to 
actually do it I'm suprised just how many things could actually be 
simplified if there was an official way to do this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Tiled Image viewer

2005-02-21 Thread Ian McConnell
Does anyone know of a widget or sample code for viewing huge (ie bigger than
RAM) images in python? The usual way of doing this is to read part of the
image into memory as a set of tiles and then zoom and pan the tiles.

The sort of thing I'm trying to achive is at

http://iipimage.sourceforge.net/IIPDemo.html

but I'd like to be able to do something like this with python (wxpython).
The other problems are that I don't really want a client/server (just a
single executable) and I have a funny image format (100s MB of matrix data)
so making the image pyramids would be a little tricky.

I've found Matt Kimballs pan and zoom widget


http://web.archive.org/web/20030810111006/http://matt.kimball.net/image_view.html

but this still reads the whole image into memory. Is there something similar
to image_view.py, but which also does tiling?

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


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread TZOTZIOY
On 21 Feb 2005 06:48:19 -0500, rumours say that Dan Sommers <[EMAIL PROTECTED]>
might have written:

[snip: snacktime posts code to count bits]

>> Seems to work, is there a better way to do this?

[Dan]
>for c in range( 128 ):
>even_odd = 0
>print '%3d' % c,
>while c:
>c &= c - 1
>even_odd = not even_odd
>print int( even_odd )

Just for the sake of people who haven't messed with bit manipulation in C or
assembly, the effect of

c &= c - 1

is to reset the rightmost (less significant) '1' bit of a number (ie change it
to '0').
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: segfault when calling Python from C thread

2005-02-21 Thread Greg Chapman
Fredrik Lundh wrote:

> Greg Chapman wrote:
> 
> > Your callback function needs to hold the Python GIL (and have a
> > vaild threadstate) before it calls any Python C-API functions.
> > Change the last part of it to:
> > 
> >PyGILState_STATE state;
> > 
> >/* ... */
> > 
> >/* Time to call the callback */
> > 
> >state = PyGILState_Ensure();
> > 
> >arglist = Py_BuildValue("(s)", str);
> >result = PyEval_CallObject(my_callback, arglist);
> >Py_DECREF(arglist);
> >if(result == NULL)
> >return;
> >Py_DECREF(result);
> > 
> >PyGILState_Release(state);
> > }
> 
> you might wish to make sure you release the GIL even if the callback
> raises an exception...
> 
>  

Argh, thanks for catching that.  You probably put that too politely
though (in case anyone sees this who might think that is optional): one
should absolutely make sure all code paths which call PyGILState_Ensure
have a matching call to PyGILState_Release.

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


Yet Another BLT/TkInter Install Question

2005-02-21 Thread Noelle QUEMENER
I have just installed BLT: I effectively had some problems - the same you had.
I found this:

Python GUI Setup

Here is the procedure I used to get "Fourier" working on Windows and Linux.

I wanted to use BLT for xy-plotting, partly because we used it with tcl in the 
sss project, and partly because I couldn't understand how to position the plots 
in wxPython (the
main alternative).

The only interface to BLT from Python seemed to be through Pmw (now it is 
claimed that you can get to BLT directly, but I haven't figured out how). So, I

* Downloaded the most recent version of Python (2.2) into C:\Python22 
(Windows)
* Downloaded the required packages (Numeric, FFT, etc.) and noticed that 
they installed into C:\Python22\Lib\site-packages
* Downloaded the corresponding release of Pmw into 
C:\Python22\Lib\site-packages

On the Debian Linux Windows system in B3 set up by Dan Freedman, this sufficed. 
On the CCMR RedHat system I've yet to get it to work. On Windows, I had to 
install the current
version of BLT. Following instructions from 
http://www.ifi.uio.no/~hpl/Pmw.Blt/doc/links.html, as suggested by Peter Brown 
at [EMAIL PROTECTED], I

* installed BLT into C:/Python22 using its installer: this made bin, 
include, and lib subdirectories of C:/Python22/tcl
* copied the directory C:/Python22/tcl/lib/blt2.4 into 
C:/Python22/tcl/tcl8.3
* copied the BLT DLL's into my PATH, specifically C:\Program Files\Tcl\bin.

Now my scripts worked on Windows. I now wished to roll them into a binary form 
that I could distribute. Chris Myers advised me to try the more advanced 
"Freeze" methods
developed at http://www.mcmillan-inc.com/install1.html. This took some time, 
until I read the documentation: on the first page of the Pmw documentation, it 
says that freezing
is tricky, and gives a link to doc/dynamicloader.html.

* Downloaded the installer and installed it in the Fourier directory 
(Linux) or into C:\Python22\Lib\site-packages (Windows)
* Make directory FourierFreeze in that same directory
* Make Pmw.py in that directory: python ..\Pmw\Pmw_0_8_5\bin\bundlepmw.py 
..\Pmw\Pmw_0_8_5\lib
* copy Fourier.py, PmwBlt.py and PmwColor.py into FourierFreeze 
(instructions from dynamicloader?)
* MAKE SURE for Linux that you remove all ^M's from the file. Also, the 
freeze program doesn't like tabs mixed with spaces, I think. The error message 
is inscrutable
* python ../Installer/Makespec.py --onefile --tk --debug --noconsole 
Fourier.py
* python ../Installer/Build.py Fourier.spec


AND IT WORKS!!!
adapt Python22 to your version (I personnally have Python 2.3.5 and 
blt24z-for-tcl84.exe)


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


Re: lambda closure question

2005-02-21 Thread Antoon Pardon
Op 2005-02-21, Diez B. Roggisch schreef <[EMAIL PROTECTED]>:
>> But I'll get back at what seems you actually wanted to say:
>> That there is no way to rebind 'x' or in my case 'l' and
>> with that I have to agree although I personnaly find that
>> a lack in python
>
> It's not only that way in python, but in java too. So it seems that there is
> a fundamental principle behind it: In a language that allows sideeffects,
> these will actually happen.
>
> If you're after side-effect free programming, I recommend using a functional
> programming language like ocaml or haskell. In these, you can't mutate
> objects at all, only recreate them and rebind them to new variables. This
> prevents whole classes of errors - but of course it also introduces all
> kinds of other constraints on your programming style, e.g. using monads and
> so on.
>

I have the impression that you misunderstood me. I'm not after a
side-effect free language. I just think python could be nicer in
allowing some side-effects.

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


Detecting the change of screen resolution with SDL or PyGame

2005-02-21 Thread Erik Bethke
Hello All,

I am trying to clean up some polish bugs with the Shanghai game I am
working on and I am currently stuck on trying to get the right event
for detecting when the user has changed the desktop resolution.

I have tried trapping the following events:

1) SDL_ACTIVEEVENT
2) SDL_VIDEOEXPOSE
3) SDL_VIDEORESIZE

These are the events that are passed through to pygame as
pygame.ACTIVEEVENT and so on...

#3 - SDL_VIDEORESIZE  This is what I looked at first and I was wrong,
this is only for the WINDOW being resized... not the desktop resoltion

#2 - SDL_VIDEOEXPOSE  After watching the events in a debugger when I
change the desktop resolution I find out that this IS the event that is
generated from changing the desktop resolution.  Okay no problem right?
 Time to call:

self.screen = self.pygame.display.set_mode( size )

and draw() again right?

Well sure, now my game repaints properly when the desktop resolution
changes.  So What is the problem?  Well now EVERY TIME another window
draws on top of my game's window a SDL_VIDEOEXPOSE event is triggered.
There does not appear to be any flags associated with this event.  So I
am having trouble distinguishing from an overlapping window and
changing the desktop resolution.

So I tried this:

1) call pygame.display.Info() at the startup of my game and save off
this structure
2) call it again after getting a SDL_VIDEOEXPOSE event and comparing to
see if it has changed at all.

The problem with this is that apparantly the VidInfo structure DOES NOT
change when changing desktop resolution...

So then I tried using SDL_ACTIVEEVENT and simply leaving the display
black and unpainted after the user changes the resolution until the
user rolls the mouse over the game window and bringing it back to
focus.

This works.  However, it gets annoying watching the screen repaint
everytime the window gains focus

Do you guys have any leads for me to try?  This HAS to be a problem
solved many times before...

Thank you,
-Erik

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


Re: lambda closure question

2005-02-21 Thread Paul Rubin
"Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
> It's not only that way in python, but in java too. So it seems that there is
> a fundamental principle behind it: In a language that allows sideeffects,
> these will actually happen.

Can you even have nested functions in Java?  Algol-60 did things the
way you'd expect, i.e. you can modify the outer variable from the
inner scope.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recommended way of generating HTML from Python

2005-02-21 Thread Matt Goodall
On Mon, 2005-02-21 at 07:36 -0500, Kent Johnson wrote:
> Michele Simionato wrote:
> > The problem is a problem of standardization, indeed. There plenty of
> > recipes to
> > do the same job, I just would like to use a blessed one (I am teaching
> > a Python
> > course and I do not know what to recommend to my students).
> 
> Why not teach your students to use a template system?
> 
> > FWIW, here is a my version of the recipe (stripped down to the bare
> > essentials)
> > 
> > .def makeattr(dict_or_list_of_pairs):
> > .dic = dict(dict_or_list_of_pairs)
> > .return " ".join("%s=%r" % (k, dic[k]) for k in dic)
> > 
> > .class HTMLTag(object):
> > .def __getattr__(self, name):
> > .def tag(value, **attr):
> > ."""value can be a string or a sequence of strings."""
> > .if hasattr(value, "__iter__"): # is iterable
> > .value = " ".join(value)
> > .return "<%s %s>%s\n" % (name, makeattr(attr), value,
> > name)
> > .return tag
> > 
> > # example:
> > .html = HTMLTag()
> > 
> > .tableheader = ["field1", "field2"]
> > .tablebody = [["a1", "a2"],
> > . ["b1", "b2"]]
> > 
> > .html_header = [html.tr(html.th(el) for el in tableheader)]
> > .html_table = [html.tr(html.td(el) for el in row) for row in tablebody]
> > .print html.table(html_header + html_table)
> 
> *Shudder*
> 
> I've written web pages this way (using a pretty nice Java HTML generation 
> package) and I don't 
> recommend it. In my experience, this approach has several drawbacks:
> - as soon as the web page gets at all complex, the conceptual shift from HTML 
> to code and back is 
> difficult.
> - It is hard to work with a designer. The designer will give you sample web 
> pages which then have to 
> be hand-translated to code. Changes to the web page have to be located in the 
> code.
> - There is no separation of content and presentation

Slightly off topic but, just to be clear, Nevow supports XHTML templates
*and* stan tag expressions.  Both are useful. As a general rule, I stick
to XHTML templates but I use stan for prototyping pages and when marking
up the XHTML templates gets so complicated that they might as well be
written in Python anyway.

Also, just because the HTML code is not in a .html file does not
necessarily mean that content and presentation are mixed up. For
instance, with stan (and probably the alternatives mentioned in this
thread) it's very easy to build a tag library that the "real" Python
code simply calls on to render page content.

> 
> IMO templating systems are a much better solution. They let you express HTML 
> in HTML directly; you 
> communicate with a designer in a language the designer understands; you can 
> separate content and 
> presentation.

Agreed. Although I would go further and say that it's important to
choose a templating system that allows the Python developer to annotate
XHTML templates using **valid XML**, i.e. no "for x in y" loops, no "if
foo" conditionals, no "i = 0" variable setting, no expression
evaluations, etc.



The lovely thing about Nevow is that it encourages good separation -
HTML is HTML and logic is Python, as it should be - but does not get in
the way when breaking the rules is necessary or just a lot easier.



Cheers, Matt

-- 
 __
/  \__ Matt Goodall, Pollenation Internet Ltd
\__/  \w: http://www.pollenation.net
  __/  \__/e: [EMAIL PROTECTED]
 /  \__/  \t: +44 (0)113 2252500
 \__/  \__/
 /  \  Any views expressed are my own and do not necessarily
 \__/  reflect the views of my employer.

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


Re: Platform independent adduser script?

2005-02-21 Thread Gustavo Rahal
Hi
On redhat you can use a libuser module that provides some highlevel 
system tasks.
redhat-tools use this module all the time.. look at some sources

Gustavo
morphex wrote:
Hi there,
does anyone here know of a script that enables adding of users on UNIX
platforms via python?
Thanks,
Morten
--
http://mail.python.org/mailman/listinfo/python-list


Re: lambda closure question

2005-02-21 Thread Diez B. Roggisch
Paul Rubin wrote:

> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
>> It's not only that way in python, but in java too. So it seems that there
>> is a fundamental principle behind it: In a language that allows
>> sideeffects, these will actually happen.
> 
> Can you even have nested functions in Java?  Algol-60 did things the
> way you'd expect, i.e. you can modify the outer variable from the
> inner scope.

Not nested functions, but closures in anonymous inner classes - which can
reference only final variables, thus creating the same effect as the
scoping rules of python.

-- 
Regards,

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


Re: lambda closure question

2005-02-21 Thread Diez B. Roggisch
> I have the impression that you misunderstood me. I'm not after a
> side-effect free language. I just think python could be nicer in
> allowing some side-effects.

Yeah, seems as if I somehow added an inadvertent "not" somewhere in my train
of thoughts while reading (and hopfully comprehending...) your post. Sorry.
-- 
Regards,

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


Re: Article on Hi-Fi Myths

2005-02-21 Thread Grant Edwards
On 2005-02-21, Mike Meyer <[EMAIL PROTECTED]> wrote:

>>  "you just need to know what techniques to use to create a
>>  'friendly', 'relaxing', energy pattern."
>
> I find that playing back Python code over multi-stranded copper
> produces the best results.

Only if you color the edges with a green marker first...

-- 
Grant Edwards   grante Yow!  MERYL STREEP is my
  at   obstetrician!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread Grant Edwards
On 2005-02-20, Nick Vargish <[EMAIL PROTECTED]> wrote:
> "BrainDead" <[EMAIL PROTECTED]> writes:
>
>> I believe that you are wasting your time.  Looking at your email
>> address, this may well be relevant.
>   [ 4-line URL snipped ]
>
> Thanks for the historical reference. Please consider a visit to
> tinyurl.com before posting a monster like that... :^)

I've never understood the problem with long URLs.  Many
newsreaders let you click on them.  If not, you just cut/paste
it into a browser (with a shellscript a couple lines long, you
can start firefox with the URL on the X clipboard with a single
command).

-- 
Grant Edwards   grante Yow!  I'm a GENIUS! I
  at   want to dispute sentence
   visi.comstructure with SUSAN
   SONTAG!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Python 2.4 Quick Reference available

2005-02-21 Thread TZOTZIOY
On Sun, 20 Feb 2005 14:57:14 +, rumours say that Michael Hoffman
<[EMAIL PROTECTED]> might have written:

[snip: use 'open' in preference to 'file']

>To be honest I doubt open will be extended in this manner. I can see
>the Pythoneers adding, say, a keyword argument to open to allow a URL
>instead, but just changing the current behavior would be too risky. Plus,
>what happens if I have a file named "http://www.python.org/";?

I don't know in what filesystem you can have such a file name [1].  Slashes
('/') you can (kind of) get away with using \u2215 (DIVISION SLASH) on NTFS or
on UTF-8 encoded *nix filenames, but I haven't found a replacement for colon
(':').  Using similar glyphs, of course, invalidates the URL...


[1] Unless you mean it as a *path name*, which /could/ exist on *nix filesystems
(normalised to a directory called 'www.python.org' in the local subdirectory
'http:'), but still could not on NTFS.
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread Ilias Lazaridis
Nick Vargish wrote:
Ilias Lazaridis <[EMAIL PROTECTED]> writes:
Now it's really time to close this thread.
I suspect this will fall of deaf ears, but I have to mention that you
 do not get to "close threads" on Usenet.
this is obvious.
You can excuse yourself from this one and stop replying to comments,
but you don't get to unilaterally declare a discussion over.
[...]
The discussion is over.
At least the in-topic one.
Everything else is babbling, hairsplitting, playing an AI which does not 
understand writings and all this unproductive garbage.

The Essence is this one, as stated before:
"
Summarized Suggestions for the Python Team, PSF, Community):
-
-
-
An automated-build-process-system should allow community-members to add 
their targets (e.g. MinGW) into an special "incubation section", which 
does not in any way affect the "main section" (which contains the 
official production targets, e.g. MSVC).

If an "incubation section" target proves over time as stable and 
supported (by community contributions), it is moved to the 
"official-auto-build".

-
The python-team should
 * detect any efforts made within the community to support different 
build-targets
 * attract/engourage the authors/teams to include the patches/sources 
into the main build-system
 * attract/engourage the authors/teams to have open projects with an 
collaboration infrastructure.

-
The python-community and the PSF should support the python-team to 
fulfill the above tasks, thus the python-teams effort is limited to 
provide the infrastructure (incubation-build-targets).

-
-
-
Practical example:
Engourage the current pyMinGW project to become a open collaborative 
project:

http://jove.prohosting.com/iwave/ipython/pyMinGW.html
  * as a first step, setup a pyMinGW mailinglist
* intrested people can come together an communicate
  * as a second step, setup an SVN
* intrested projects could get your patch via SVN
  * as a third step, find intrested contributors
* which would help testing
* which would help you with coding
The python-team setups a build-target, which the collaborative pyMinGW 
project tries to make valid.

-
-
-
Now it's really time to close this thread.
.
"
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: lambda closure question

2005-02-21 Thread jfj
Carl Banks wrote:
transformations gets rebound, so you'd need a reference to it.
That certainly is an application.  I guess it depends on one's
programming background.
I'd only use nested (function, class) definition to accomplish
such a feature:

def genclass(x,y):
class myclass:
M = x
def f(self, z):
return self.M + y + z
return myclass
A=genclass(1,2)
a=A()
#
where i would prefer python to expand this as a template to:
class myclass:
M = 1
def f(self, z):
return self.M + 2 + z
A = myclass
a = A()
IOW, I'd like nested (function, class) definitions to
be used *only* for dynamic code generation with runtime
constants, and OOP *forced* for other applications like
the fractal example:)
jf
---
# if you're dissatisfied with the situation on the planet
# slow down the circulation of money
--
http://mail.python.org/mailman/listinfo/python-list


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread Diez B. Roggisch
> I've never understood the problem with long URLs.  Many
> newsreaders let you click on them.  If not, you just cut/paste
> it into a browser (with a shellscript a couple lines long, you
> can start firefox with the URL on the X clipboard with a single
> command).

Some break the urls - so copy and pasting yields only start or end of the
urls, depending on the browser/edit control your pasting into.

-- 
Regards,

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


Re: help please

2005-02-21 Thread rzed

"gargonx" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Even if i put it in exactly the way you did:
>
> >>> import re
> >>> charmatcher = re.compile(r' [A-Z] [\d]?')
> >>>
> >>> ext = dict(D="V1", O="M1", G="S1")
> >>> std = dict(S="H")
> >>>
> >>> decode_replacements ={}
> >>> decode_replacements.update([(std[key], key) for key in std])
> Traceback (most recent call last):
>   File "", line 1, in ?
> AttributeError: keys


Works with 2.4, but not with 2.3.4:

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> charmatcher = re.compile(r' [A-Z] [\d]?')
>>>
>>> ext = dict(D="V1", O="M1", G="S1")
>>> std = dict(S="H")
>>>
>>> decode_replacements ={}
>>> decode_replacements.update([(std[key], key) for key in std])
>>>
>>> print decode_replacements
{'H': 'S'}



Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> charmatcher = re.compile(r' [A-Z] [\d]?')
>>>
>>> ext = dict(D="V1", O="M1", G="S1")
>>> std = dict(S="H")
>>>
>>> decode_replacements ={}
>>> decode_replacements.update([(std[key], key) for key in std])
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: keys
>>>
>>> print decode_replacements
{}




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


detecting the change in desktop resolution - how?

2005-02-21 Thread Erik Bethke
Hello All,

I am trying to clean up some polish bugs with the Shanghai game I am
working on and I am currently stuck on trying to get the right event
for detecting when the user has changed the desktop resolution.

I have tried trapping the following events:

1) SDL_ACTIVEEVENT
2) SDL_VIDEOEXPOSE3) SDL_VIDEORESIZE

These are the events that are passed through to pygame as
pygame.ACTIVEEVENT and so on...

#3 - SDL_VIDEORESIZE  This is what I looked at first and I was wrong,
this is only for the WINDOW being resized... not the desktop resoltion

#2 - SDL_VIDEOEXPOSE  After watching the events in a debugger when I
change the desktop resolution I find out that this IS the event that is
generated from changing the desktop resolution.  Okay no problem right?
 Time to call:

self.screen = self.pygame.display.set_mode( size )

and draw() again right?

Well sure, now my game repaints properly when the desktop resolution
changes.  So What is the problem?  Well now EVERY TIME another window
draws on top of my game's window a SDL_VIDEOEXPOSE event is triggered.
There does not appear to be any flags associated with this event.  So I
am having trouble distinguishing from an overlapping window and
changing the desktop resolution.

So I tried this:

1) call pygame.display.Info() at the startup of my game and save off
this structure
2) call it again after getting a SDL_VIDEOEXPOSE event and comparing to
see if it has changed at all.

The problem with this is that apparantly the VidInfo structure DOES NOT
change when changing desktop resolution...

So then I tried using SDL_ACTIVEEVENT and simply leaving the display
black and unpainted after the user changes the resolution until the
user rolls the mouse over the game window and bringing it back to
focus.

This works.  However, it gets annoying watching the screen repaint
everytime the window gains focus

Do you guys have any leads for me to try?  This HAS to be a problem
solved many times before...

Thank you,
-Erik

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


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Bryan
Christos TZOTZIOY Georgiou wrote:
On 21 Feb 2005 06:48:19 -0500, rumours say that Dan Sommers <[EMAIL PROTECTED]>
might have written:
[snip: snacktime posts code to count bits]

Seems to work, is there a better way to do this?

[Dan]
for c in range( 128 ):
  even_odd = 0
  print '%3d' % c,
  while c:
  c &= c - 1
  even_odd = not even_odd
  print int( even_odd )

Just for the sake of people who haven't messed with bit manipulation in C or
assembly, the effect of
c &= c - 1
is to reset the rightmost (less significant) '1' bit of a number (ie change it
to '0').
i tried c &= c - 1 but i'm not getting the least significant or rightmost bit 
reset to zero.  am i misunderstanding something?

>>> 2 & 1  # 2 = 0x10; reset right most would be 0x10
0
>>> 10 & 9 # 10 = 0x1010; reset right most would be 0x1010
8
bryan
--
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE Problem: win98\Python2.4

2005-02-21 Thread rmb25612

kim kubik wrote:
> This sure seems like it would have been
> brought up but I checked Google Groups
> (the dejanews replacement) and saw
> nothing:  I installed Python2.4 in Win98
> and IDLE doesn't work (neither does the
> online manual even tho a 3.6KB Python24.chm
> is there, but that's a story for another
> day) - that is, clicking on the IDLE icon
> in the Start menu just gives a brief hourglass
> cursor and then nothing . . .

Are you also running Ruby? The Ruby bundle for MS Windows has caused
problems with it's TCL package conflicting with Python's.

Search comp.lang.python on Google Groups for: Ruby TCL

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


Unittest - testing properties (read-only attributes)

2005-02-21 Thread Paul Moore
I have a class with a read-only attribute, and I want to add a unit
test to ensure that it really *is* read-only. I can do this as

def test_readonly(self):
"""Value and multiplier must be readonly"""
try:
self.combat.value = 1
self.fail("Value is not read only")
except AttributeError:
pass

That works, but it seems a bit clumsy. Is there a better way?

Thanks,
Paul.
-- 
XML with elementtree is what makes me never have think about XML
again. -- Istvan Albert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Diez B. Roggisch
Paul Moore wrote:

> I have a class with a read-only attribute, and I want to add a unit
> test to ensure that it really *is* read-only. I can do this as
> 
> def test_readonly(self):
> """Value and multiplier must be readonly"""
> try:
> self.combat.value = 1
> self.fail("Value is not read only")
> except AttributeError:
> pass
> 
> That works, but it seems a bit clumsy. Is there a better way?


By using setattr, you could refactor the above code into a function. Looks
like this (untested):

def test_readonly(self, instance, attribute, value=1):
 """Value and multiplier must be readonly"""
 try:
setattr(instance, attribute, value)
self.fail("Value is not read only")
 except AttributeError:
pass


Then the testing becomes one line:

self.test_readonly(self.combat, "value")


-- 
Regards,

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


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Roy Smith
In article <[EMAIL PROTECTED]>, Paul Moore <[EMAIL PROTECTED]> 
wrote:

> I have a class with a read-only attribute, and I want to add a unit
> test to ensure that it really *is* read-only. I can do this as
> 
> def test_readonly(self):
>   """Value and multiplier must be readonly"""
>   try:
>   self.combat.value = 1
>   self.fail("Value is not read only")
>   except AttributeError:
>   pass
> 
> That works, but it seems a bit clumsy. Is there a better way?
> 
> Thanks,
> Paul.

You want something like

self.assertRaises(AttributeError, lambda: self.combat.value = 1)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: detecting the change in desktop resolution - how?

2005-02-21 Thread Do Re Mi chel La Si Do
Hi !

On windows, and PyWin, this script give the H/V current resolution :



import win32com.client
oWMI = win32com.client.Dispatch("WbemScripting.SWbemLocator")
owbem = oWMI.ConnectServer(".","root\cimv2")
collec = owbem.ExecQuery("Select * from Win32_PrinterConfiguration")
print "Horizontal Resolution: ", collec[0].HorizontalResolution
print "Vertical Resolution: ", collec[0].VerticalResolution




@-salutations
-- 
Michel Claveau





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


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Peter Hansen
Roy Smith wrote:
You want something like
self.assertRaises(AttributeError, lambda: self.combat.value = 1)
Or, combining the two responses and avoiding the lambda:
 self.assertRaises(AttributeError, setattr, self.combat, 'value', 1)
Hmm... this might be a case where the lambda form is actually the
more readable one...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Paul Rubin
Peter Hansen <[EMAIL PROTECTED]> writes:
> > You want something like
> > self.assertRaises(AttributeError, lambda: self.combat.value = 1)
> 
> Or, combining the two responses and avoiding the lambda:
> 
>   self.assertRaises(AttributeError, setattr, self.combat, 'value', 1)
> 
> Hmm... this might be a case where the lambda form is actually the
> more readable one...

Yes, assignment expressions could make code more readable, if Python
supported them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Duncan Booth
Bryan wrote:

>> is to reset the rightmost (less significant) '1' bit of a number (ie
>> change it to '0').
> 
> i tried c &= c - 1 but i'm not getting the least significant or
> rightmost bit reset to zero.  am i misunderstanding something?
> 
> >>> 2 & 1  # 2 = 0x10; reset right most would be 0x10
> 0
> >>> 10 & 9 # 10 = 0x1010; reset right most would be 0x1010
> 8

The difference between the original "reset the rightmost '1' bit", and your 
interpretation: "reset the rightmost bit" is the "'1'".

The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000.

If you want to extract the least significant set bit from a number 'x' you 
can use (x&-x):

>>> x = 0xab4
>>> while x:
print hex(x&-x), hex(x)
x ^= (x&-x)


0x4 0xab4
0x10 0xab0
0x20 0xaa0
0x80 0xa80
0x200 0xa00
0x800 0x800
>>> 

(but don't try this if x is negative: it works but never terminates).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread George Sakkis
"Ilias Lazaridis" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]

> Nick Vargish wrote:
> > You can excuse yourself from this one and stop replying to comments,
> > but you don't get to unilaterally declare a discussion over.
> [...]
>
> The discussion is over.
>
> At least the in-topic one.
>
> Everything else is babbling, hairsplitting, playing an AI which does not
> understand writings and all this unproductive garbage.
>
> The Essence is this one, as stated before:
>
> [huge copy paste of previous post]


The Essence is irrelevant.
-
-
-
All your thread are belong to us.
-
-
-

George






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


Re: recommended way of generating HTML from Python

2005-02-21 Thread Michele Simionato
Kent Johnson:
>I've written web pages this way (using a pretty nice Java HTML
generation package) >and I don't
>recommend it. In my experience, this approach has several drawbacks:
>- as soon as the web page gets at all complex, the conceptual shift
from HTML to >code and back is
>difficult.
>- It is hard to work with a designer. The designer will give you
sample web pages >which then have to
>be hand-translated to code. Changes to the web page have to be located
in the code.
>- There is no separation of content and presentation

>IMO templating systems are a much better solution. They let you
express HTML in >HTML directly; you
>communicate with a designer in a language the designer understands;
you can >separate content and
>presentation

You make a series of good points I am well aware of; however, still
there are
places were direct HTML generation can be a reasonable approach (my use
case was the formatting of a SQL query): cases where the result will
never
ever touch a designer. Also, one could argue that the designer should
not
get in touch with the HTML, but just play with the CSS.
Finally, you can achieve separation between logic and presentation just
putting the
routines generating the HTML pages in a separate module, no need to use
a
different language.

Michele Simionato

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


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Paul Moore
Peter Hansen <[EMAIL PROTECTED]> writes:

> Roy Smith wrote:
>> You want something like
>> self.assertRaises(AttributeError, lambda: self.combat.value = 1)
>
> Or, combining the two responses and avoiding the lambda:
>
>  self.assertRaises(AttributeError, setattr, self.combat, 'value', 1)
>
> Hmm... this might be a case where the lambda form is actually the
> more readable one...

Thanks, I hadn't thought of setattr. I was bitten by the "assignment
is a statement, so can't be used in a lambda" issue, as well :-)

Paul.
-- 
It was a machine, and as such only understood one thing. Being clobbered
with big hammers was something it could relate to. -- Tom Holt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exercise: partition a list by equivalence

2005-02-21 Thread Reinhold Birkenfeld
John Machin wrote:
> Reinhold Birkenfeld wrote:
>> Reinhold Birkenfeld wrote:
>>
>> > My solution (which may not be the fastest or most effective, but
> till
>> > now is the shortest  and it works):
> 
> [snip RB]
>>
>> A recursive solution (around twice as fast as the above, though very
>> slow still...)
>>
> [snip RB2]
>>
>> Another one:
>>
> 
> [snip RB3]
> 
> Dunno what data you are using for timing, but my tests suggest that RB
> is fast enough, RB3 is slightly faster, but RB2 is a real dog and
> appears to be quadratic [hint: it has that same for-for-for-update
> signature found in phase 2 of Xah's effort]. Not only that, but it
> seems to be somewhat irregular. Below are some results on trivial test
> data:
[snip]

Yes, I don't know exactly how I timed this, and I just posted the
solutions to show that there are very different solutions possible. They
are surely not using the best algorithms, as bearophile's function showed.

Reinhold

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


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Duncan Booth
Paul Rubin wrote:

> Peter Hansen <[EMAIL PROTECTED]> writes:
>> > You want something like
>> > self.assertRaises(AttributeError, lambda: self.combat.value = 1)
>> 
>> Or, combining the two responses and avoiding the lambda:
>> 
>>   self.assertRaises(AttributeError, setattr, self.combat, 'value', 1)
>> 
>> Hmm... this might be a case where the lambda form is actually the
>> more readable one...
> 
> Yes, assignment expressions could make code more readable, if Python
> supported them.
> 

An assignment expression, if such a thing existed wouldn't help here.

The point being that the expression must be evaluated inside the exception 
handler in assertRaises, so you either need to delay the evaluation with a 
lambda, or by passing the function and arguments in separately. If you had 
an assignment expression it would be roughly equivalent to:

   self.assertRaises(AttributeError, setattr(self.combat, 'value', 1))

which will throw the AttributeError instead of passing the test.

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


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Duncan Booth
Duncan Booth wrote:

> An assignment expression, if such a thing existed wouldn't help here.

Although of course it would help if still inside a lambda.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Brian Beck
Duncan Booth wrote:
The difference between the original "reset the rightmost '1' bit", and your 
interpretation: "reset the rightmost bit" is the "'1'".

The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000.
If you want to extract the least significant set bit from a number 'x' you 
can use (x&-x):
My interpretation of Bryan's (mis?)interpretation (heh) was that since 
in the numbers 2 and 10 (as in his examples), the least significant bit 
was already 0, performing an operation that set it to 0 should result in 
the number unchanged. As his tests show, this is not the case. This is 
because the operation works only if the least significant bit actually 
NEEDS to be unset. To zero the least significant bit unconditionally, we 
can use:

x &= ~1
--
Brian Beck
Adventurer of the First Order
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Paul Rubin
Duncan Booth <[EMAIL PROTECTED]> writes:
> An assignment expression, if such a thing existed wouldn't help here.
> 
> The point being that the expression must be evaluated inside the exception 
> handler in assertRaises, so you either need to delay the evaluation with a 
> lambda, or by passing the function and arguments in separately. If you had 
> an assignment expression it would be roughly equivalent to:
> 
>self.assertRaises(AttributeError, setattr(self.combat, 'value', 1))
> 
> which will throw the AttributeError instead of passing the test.

Yes.  The example I quoted used an assignment expression inside a
lambda.  The person who posted it, and the person who followed it up
with the setattr alternative, both didn't notice that the assignment
expression wasn't valid Python.  However, my post came out sounding
grumpier than I intended ;).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE Problem: win98\Python2.4

2005-02-21 Thread kim kubik

>   kim kubik wrote:
> > I installed Python2.4 in Win98
> > and IDLE doesn't work

> Are you also running Ruby? The Ruby bundle for MS Windows has caused
> problems with it's TCL package conflicting with Python's.
>
thanks, one of the first things I noted in the error msg
(not included for brevity) was that the ruby search
path in AUTOEXEC.BAT was ahead of the python path (and
ruby had tcl83.lib) so I REM'd all the tcl stuff out.
AND THEN (stupid me!) I put into AUTOEXEC.BAT
'set TCL_LIBRARY=c:\python23\tcl'  thinking that
would point python to the proper libs. What a mistake!
If I take that line out (and leave the ruby stuff REM'd
out as well) IDLE runs just fine. So thanks!

A little knowledge is indeed a dangerous thing; forgive my
stupidity - it will happen again, so I'm apologizing in advance!
\kim


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


Re: Unittest - testing properties (read-only attributes)

2005-02-21 Thread Roy Smith
Paul Rubin  wrote:
>  The example I quoted used an assignment expression inside a
> lambda.  The person who posted it,

That was me.

> and the person who followed it up
> with the setattr alternative, both didn't notice that the assignment
> expression wasn't valid Python.

Ugh.  No, I hadn't noticed it.  Thanks for pointing it out.

I don't use lambdas much.  In fact, the only time I ever do use them is for 
an assertRaises unit test.  I've always thought that "assignment is  a 
statement not an expression" was one of Python's warts, and this is just 
another example of why it is.  Of course, "lambda isn't just a def body" is 
a wart too :-)

> However, my post came out sounding
> grumpier than I intended ;).

Actually, I hadn't noticed that either. :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: recommended way of generating HTML from Python

2005-02-21 Thread Robert Brewer
Michele Simionato wrote:
> The problem is a problem of standardization, indeed.
> There are plenty of recipes to do the same job, I just
> would like to use a blessed one (I am teaching a Python
> course and I do not know what to recommend to my students).

Wouldn't we *all* like all of our problems worked out for us. ;)

> class HTMLTag(object):
> [wonderful code snipped]

That's a reasonable start, and you have some fun magic in there, but I think 
you're going to hit a wall of complexity Real Soon Now--elements without a 
separate closing tag, safe attribute quoting, and general usability pressures 
will start to bite you. I note also what Kent said about separation, and the 
desire to "hand things off to a web designer".

In my own work, I tried to meet both of these concerns with a single Assembly 
class, which you can see at http://www.aminus.org/rbre/cation/html/assembly.py. 
At its most basic, it is nothing more than a namespace plus a template. I think 
it solves the separation issue nicely by allowing the template to be loaded 
from a file, whether that file be HTML from a designer, HTML "bulding blocks" 
which a developer might supply, or even CSS, or an email template. But it also 
allows for useful subclassing, for code generation. Here's an example: the 
subclass for "hidden input" elements:

class HiddenElement(Assembly):
"""An Assembly for generating HTML  elements

Usage:
output = assembly.HiddenElement(app).assemble_all(key)
"""

templateText = u''

def assemble_all(self, name, value):
return self.assemble({u'name': html.quote(name),
  u'value': html.quote(value)})

The "assemble_all" method allows the developer to focus on the important bits 
(name and value) and forget the implementation details. Check out the TableRows 
class for a more complex example, whereby an HTML table can be built 
incrementally, inline with the data access logic.

Now, getting into usability concerns (that framework and library authors tend 
to obsess over ;) may be too advanced for your class at the moment. But that's 
why recipes are recipes, not standard library modules: they're often biased 
toward quick and dirty scripting, not usable, maintainable edifices.


Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: recommended way of generating HTML from Python

2005-02-21 Thread has
Kent Johnson wrote:
> Michele Simionato wrote:
> > The problem is a problem of standardization, indeed. There plenty
of
> > recipes to
> > do the same job, I just would like to use a blessed one (I am
teaching
> > a Python
> > course and I do not know what to recommend to my students).
>
> Why not teach your students to use a template system?

Agreed. Don't use HTML generation simply for the sake of it. While it
has its niche, for most tasks templating is more appropriate. There
aren't any 'blessed' solutions, so just pick whichever third-party
system best fits your needs.

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


ANNOUNCE: SiGeFi v0.3

2005-02-21 Thread Batista, Facundo
Title: ANNOUNCE: SiGeFi v0.3






We're proud to announce the 0.3 version of SiGeFi, which you can find
at:


    http://sourceforge.net/projects/sigefi


    
What is SiGeFi?
---


SiGeFi is a Financial Management System, with focus in the needs of
the administration of the money in each personal life and house.


Always keeping the easy usage and concepts, SiGeFi has features of a 
complex Management system:


- Complies with Double Entry Accounting


- Has a Budget-based Money Distribution system


- Allow to make Loans between accounts (with associated financial
  costs)


And of course, it's completely written in Python (didn't decided the
GUI yet).



What is in this version?



Functionality change:
- Added the LoanChecker, a programmable asynchronous alert that verifies
  the loans due date.


Internal changes:
- Ended the docstrings, and generated the classes documentation using
  epydoc (that soon will be published in the web as part of its content).
- Translated all the code texts to English, and did the gettext integration,
  so now SiGeFi is multilanguage (so far we have English and Spanish only).
- Bugfixing.


Specified the SiGeFi graphic interface. In the manual-gui.html document we
described each window's functionality, and also we added an image for each
one, so if you want to have a preview of how the GUI will look, there you
have it).


See roadmap.txt to find out the milestone for each version.


Be aware that most of the documentation is not translated yet, it's only
in Spanish.



What can I expect for the next version?
---


To us to finish the GUI (with all that that implies) and some other
improvements:


- See if we replace the PersitentDict with a shelve.
- Study the consistency controls of Pickle, and implement some if
  necessary.
- Define the boot procedure and code it in config.py.
- Set up the web page.



How can I help?
---


In a thousand ways, there's a lot of things to do: documentation,
fixing code, translations, set up the web page, etc...


If you want to participate, send us a mail to the list 
([EMAIL PROTECTED]) or directly to us.



Thank you.


.    Facundo


Bitácora De Vuelo: http://www.taniquetil.com.ar/plog
PyAr - Python Argentina: http://pyar.decode.com.ar/



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

Re: Test for structure

2005-02-21 Thread Steven Bethard
> Steven Bethard wrote:
>>
>>Right.  str and unicode objects support iteration through the old
>>__getitem__ protocol, not the __iter__ protocol.  If you want to use
>>something as an iterable, just use it and catch the exception:
>>
>>try:
>> itr = iter(a)
>>except TypeError:
>> # 'a' is not iterable
>>else:
>> # 'a' is iterable
Martin Miller broke the order of reading by top-posting:
In either case, you can't tell a string and list apart, which is what
the OP wanted to know, namely how to differentiate the two.
Yes, sorry, I should have marked my post OT.  It was an answer to Terry 
Hancock's post suggesting hasattr(x, '__iter__'), not the OP.

Perhaps the test for an __iter__ attribute *is* the way to go because
you can tell the difference between the two type.
I've seen this done before, e.g.:
try:
itr = iter(x)
except TypeError:
# is not iterable
else:
if hasattr(x, '__iter__'):
# is other iterable
else:
# is str or unicode
I don't like this idea much because it depends on str and unicode _not_ 
having a particular function.  I haven't seen any guarantee anywhere 
that str or unicode won't ever grow an __iter__ method.  So this code 
seems dangerous as far as future compatibility goes.

I think the technique suggested by Robin Munn nearly a year ago (and
referenced by the link in Simon Brunning's post):
http://groups-beta.google.com/group/comp.lang.python/msg/c8befd4bed517bbc
namely:
try:
a + ''
except TypeError:
pass
else:
a= [a]
would be a good usable solution, although it's not totally infallible.
Yup, if I had to do this kind of type-checking (which I don't think I 
ever do), I'd probably go with something along these lines.

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


Re: combining several lambda equations

2005-02-21 Thread Steven Bethard
Antoon Pardon wrote:
So and if I have code like this:
f = lamda x:x 
for g in some_iter:
  f = compose(g,f)

Do you still think that one should use a named function in this case?
Yes.  If you really don't like taking two lines, Python still allows you 
to write this as:

def f(x): return x
for g in some_iter:
f = compose(g, f)
On the other hand, if you really love FP enough to write this kind of 
code, shouldn't you be using reduce istead? ;)  I'm horrible with 
reduce, but something like:

def identity(x):
return x
f = reduce(compose, some_iter, identity)
or if you want to use lambda (note that my complaint about making an 
named function with the anonymous function syntax doesn't apply here):

f = reduce(compose, some_iter, lambda x: x)
Not sure if the order of composition is right here, but you get the idea.
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


[OT] Re: lambda closure question

2005-02-21 Thread Steven Bethard
Antoon Pardon wrote:
def F():
...   l = []
...   def pop():
... return l.pop()
...   def push(e):
... l.append(e)
...   return pop, push
... 
Just a side note to point out that another way of writing this is:
py> def F():
... l = []
... return l.pop, l.append
...
You'll get the same behavior:
py> pop, push = F()
py> push(1)
py> pop()
1
py> push(2)
py> push(3)
py> pop()
3
py> pop()
2
Hooray for bound methods! ;)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: python2.4 generator expression > python2.3 list expression

2005-02-21 Thread Bryan
Duncan Booth wrote:
Bryan wrote:

is to reset the rightmost (less significant) '1' bit of a number (ie
change it to '0').
i tried c &= c - 1 but i'm not getting the least significant or
rightmost bit reset to zero.  am i misunderstanding something?

2 & 1  # 2 = 0x10; reset right most would be 0x10
0
10 & 9 # 10 = 0x1010; reset right most would be 0x1010
8

The difference between the original "reset the rightmost '1' bit", and your 
interpretation: "reset the rightmost bit" is the "'1'".

The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000.
If you want to extract the least significant set bit from a number 'x' you 
can use (x&-x):


x = 0xab4
while x:
print hex(x&-x), hex(x)
x ^= (x&-x)

0x4 0xab4
0x10 0xab0
0x20 0xaa0
0x80 0xa80
0x200 0xa00
0x800 0x800
(but don't try this if x is negative: it works but never terminates).
thanks duncan... you're right, i did intrepret this as "reset the rightmost bit" 
instead of "reset the rightmost '1' bit".  and i must have read what christos 
wrote 100 times!!!

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


Re: Test for structure

2005-02-21 Thread Martin Miller
Testing for the '__iter__' (or even '__getitem__') attribute doesn't
really address the problem, nor does trying to execute the statement
'itr = iter(a)'.

To use EAPF and answer the OP's original question, which was

> So how can I test if a variable 'a' is either a single character
> string or a list?

I think the best answer would be to use Robin Munn's suggestion (see
http://groups-beta.google.com/group/comp.lang.python/msg/c8befd4bed517bbc)
as mentioned in the link in Simon Brunning's post) namely:

try:
a + ''
except TypeError:
pass
else:
a = [a]

However, to handle the more general problem of allow *any* argument to
be either a single item or a list seems to require a combination of
both EAPF and LBYL. This is the best solution I've been able to come up
with so far:

def asList(arg):
"""Makes sure the argument it is passed is a Python list.
If it is, it is just returned, otherwise a (possibly empty)
list is created and returned with the single item in it.

asList() can used to create flexible interfaces which allow
arguments to be passed to them that are either single items or
lists of items. By applying this function before using the
values in arguments, single and multi-valued cases can be
handled by general list-handling code in the function or
method.

As a special case, a single argument with the value None is
converted into an empty list (instead of converted into the
list [None]).

asList(arg) ==> list
"""

if arg is None:
return []
elif isinstance(arg, basestring): # special case strings (to
  # avoid list())
return [arg]
else:
try:
return list(arg)
except TypeError:
return [arg]


if __name__ == "__main__":

def example(items=None):
"""Sample function that can be called with a single argument
that can be a single or list of items.
"""
itemList = asList(items)
if not itemList:
print "example() called with empty list or None argument"
else:
print "example() called with argument containing %d " \
  "thing%s" % \
  (len(itemList), ('','s')[len(itemList)>1])
for i, item in enumerate(itemList):
print "  items[%d] = %s" % (i, repr(item))

example(42)
example((1,2,3))
example([4,5,6,7])
example('abc')
example(u'def')
example(["aaa", 111, (4,5), 2.01])
example(None) #  Note that this will become an empty list
example() #  same in this case

Which produces the following output:

example() called with argument containing 1 thing
  items[0] = 42
example() called with argument containing 3 things
  items[0] = 1
  items[1] = 2
  items[2] = 3
example() called with argument containing 4 things
  items[0] = 4
  items[1] = 5
  items[2] = 6
  items[3] = 7
example() called with argument containing 1 thing
  items[0] = 'abc'
example() called with argument containing 1 thing
  items[0] = u'def'
example() called with argument containing 4 things
  items[0] = 'aaa'
  items[1] = 111
  items[2] = (4, 5)
  items[3] = 2.0098
example() called with empty list or None argument
example() called with empty list or None argument

Can this be improved or is there anything wrong or overly limiting
about it?

TIA,
Martin


=
Steven Bethard wrote:
> Terry Hancock wrote:
>  > But you probably shouldn't do that. You should probably just test
to
>  > see if the object is iterable --- does it have an __iter__ method?
>  >
>  > Which might look like this:
>  >
>  > if hasattr(a, '__iter__'):
>  > print "'a' quacks like a duck"
>
> Martin Miller top-posted:
> > I don't believe you can use the test for a __iter__ attribute in
this
> > case, for the following reason:
> >
> c1 = 'abc'
> c2 = ['de', 'fgh', 'ijkl']
> hasattr(c1, '__iter__')
> > False
> >
> hasattr(c2, '__iter__')
> > True
>
> Right.  str and unicode objects support iteration through the old
> __getitem__ protocol, not the __iter__ protocol.  If you want to use
> something as an iterable, just use it and catch the exception:
>
> try:
>  itr = iter(a)
> except TypeError:
>  # 'a' is not iterable
> else:
>  # 'a' is iterable
>
> Another lesson in why EAPF is often better than LBYL in Python[1].
> 
> STeVe
> 
> [1] http://www.python.org/moin/PythonGlossary

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


Re: unicode encoding usablilty problem

2005-02-21 Thread Dieter Maurer
"Fredrik Lundh" <[EMAIL PROTECTED]> writes on Sat, 19 Feb 2005 18:44:27 +0100:
> "aurora" <[EMAIL PROTECTED]> wrote:
> 
> > I don't want to mix them. But how could I find them? How do I know this  
> > statement can be 
> > potential problem
> >
> >   if a==b:
> >
> > where a and b can be instantiated individually far away from this line of  
> > code that put them 
> > together?

I do understand aurora's problems very well.

Me, too, I had suffered from this occasionally:

   * some library decides to use unicode (without I had asked it to do so)

   * Python decides then to convert other strings to unicode
 and bum: "Unicode decode error".

I solve these issues with a "sys.setdefaultencoding(ourDefaultEncoding)"
in "sitecustomize.py".

I know that almost all the characters I have to handle
are encoded in "ourDefaultEncoding" and if something
converts to Unicode without being asked for, then this
is precisely the correct encoding.

I know that Unicode fanatists do not like "setdefaultencoding"
but until we will have completely converted to Unicode (which we probably
will do in the farer future), this is essential to keep sane...


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


Re: multimethod (or rather overloading) in Python

2005-02-21 Thread anton muhin
Nick Coghlan wrote:
anton muhin wrote:
anton muhin wrote:
Correction:
Of course, I can imagine some metaclasses magic that would allow to 
code:

class MyClass(WithOverloading):
  @overloadMethod(A)
  def someMetod(self, _): ...
But it would rather convoluted: the best idea I have so far is to 
mangle  methods name in the manner most of C++ compilers do.

PEAK has a fairly sophisticated implementation of method dispatch you 
may want to look at.

http://peak.telecommunity.com/Articles/WhatisPEAK.html
http://dirtsimple.org/2004/11/generic-functions-have-landed.html
http://peak.telecommunity.com/doc/src/dispatch/__init__.html
I'm compelled to point out that PEAK should still be considered a 'work 
in progress', but PJE's ideas should help you out :)

Cheers,
Nick.
Thank you very much, Nick!
anton.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Real-Time Fluid Dynamics for Games...

2005-02-21 Thread Alberto Santini
You can find some screenshot in the Stam's original paper.
I didn't do any serious benchmark. I compared the speed
of C version with the Python one. It seems enough good.

I advice you to download from Stam's site paper and C code,
compile the C code and verify yourself the results.

I think the solver of Navier-Stokes equations is a piece
of cake(remember, it's patented): one page of code or less. :)

I don't like the use of global in the callback functions
of OpenGL.

-- 
Regards,
Alberto Santini


<[EMAIL PROTECTED]> ha scritto nel messaggio 
news:[EMAIL PROTECTED]
> Your two email addresses bouce emails back, so I post a shortened
> version of my comment here.
> I haven't installed:
> PyOpenGL-2.0.2.01.py2.4-numpy23
> glut-3.7.6
> Therefore at the moment I cannot try your interesting code.
> What's the speed of this Python code on your computer?
> I'd like to see a screenshoot of the running Python Program...
>
> Some people are doing in Python some things that require lots of
> computations, like:
> http://www.joachim-bauch.de/projects/python/pytrace
>
> Bye,
> Bearophile
> 


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


Re: Test for structure

2005-02-21 Thread Steven Bethard
Martin Miller broke the order of reading again by top-posting:
However, to handle the more general problem of allow *any* argument to
be either a single item or a list seems to require a combination of
both EAPF and LBYL. This is the best solution I've been able to come up
with so far:
def asList(arg):
[snip]
if arg is None:
return []
elif isinstance(arg, basestring): # special case strings (to
  # avoid list())
return [arg]
else:
try:
return list(arg)
except TypeError:
return [arg]
[snip]
Can this be improved or is there anything wrong or overly limiting
about it?
I don't think you're going to do a whole lot better than that, though 
you can try something like the following if you're really afraid of the 
isinstance:

def aslist(arg):
# you don't need to test None; it will be caught by the list branch
try:
arg + ''
except TypeError:
return [arg]
try:
return list(arg)
except TypeError:
return [arg]
That said, I find that in most cases, the better option is to use *args 
in the original function though.  For example:

def f(arg):
args = aslist(arg)
...
f(42)
f(['spam', 'eggs', 'ham'])
could probably be more easily written as:
def f(*args):
...
f(42)
f('spam', 'eggs', 'ham')
Of course this won't work if you have multiple list arguments.
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


display VARCHAR(mysql) and special chars in html

2005-02-21 Thread Jonas Meurer
hello,

my script selects a comment saved as VARCHAR in MySQL and displays it
inside an html page.

the problem is, that the comment contains several special characters, as
mysterious utf-8 hyphens, german umlauts, etc.

i could write a function to parse the comment and substitute special
chars with the relevant html code, but maybe this already exists in some
module?

if not, it'll be hard work, as i've to consider many special chars, and
at least iso-8859-1* and utf-8 as charmaps.

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


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-21 Thread Nick Vargish
Grant Edwards <[EMAIL PROTECTED]> writes:

> I've never understood the problem with long URLs.  Many
> newsreaders let you click on them.  If not, you just cut/paste
> it into a browser (with a shellscript a couple lines long, you
> can start firefox with the URL on the X clipboard with a single
> command).

I use Gnus through a screen session, so when I select and copy a long
URL I get backslash characters in the copied text (as amusing as it
is, w3 is not a satisfying browsing experience for me :^). It's not
hard to manually pick out the backslashes, but it's time consuming and
kind of tedious. I use an open-source terminal app (iTerm under OS X),
so I guess I could hack the "open in browser" function to remove the
backslashes... Hmm...

Side projects aside, URLs less than 79 characters long are just easier
to handle in many ways.

Nick

-- 
#  sigmask  ||  0.2  ||  20030107  ||  public domain  ||  feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt Python Bindings for Qt v3.14 Released

2005-02-21 Thread Jarek Zgoda
Phil Thompson napisał(a):
Riverbank Computing is pleased to announce the release of PyQt v3.14 available 
from http://www.riverbankcomputing.co.uk/.
Classes generated by puyic 3.13 are not compatible with PyQt 3.14 (some 
method signature incompatibilities). I cann't provide more details, as I 
regenerated all classes from *.ui files, but this may be reproductible.

--
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Test for structure

2005-02-21 Thread Terry Reedy

"Steven Bethard" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I don't like this idea much because it depends on str and unicode _not_ 
> having a particular function.  I haven't seen any guarantee anywhere that 
> str or unicode won't ever grow an __iter__ method.  So this code seems 
> dangerous as far as future compatibility goes.

When CPython's support for the old iteration protocol goes away, which I 
expects it will someday, strings will have to grow an __iter__ method. 
Even now, I think this difference between strings and lists is more of an 
accident than a logical design.  So the test is opaque and specific to 
current CPython.  The validity of something like a = a+'', however, is 
inherent to the nature of strings.

Terry J. Reedy



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


iterative lambda construction

2005-02-21 Thread markscottwright
Just for the hell of it, I've been going through the old Scheme-based
textbook "Structure and Interpretation of Computer Programs" and seeing
what I can and can't do with python.  I'm trying to create a function
that returns the function (not the results of the function, but a
function object) that results from applying function f to it's (single)
argument N times.  For example, if you have "def sq(x): return x*x",
then repeated(sq, 2)(2) = 16, repeated(sq, 3)(2) = 256, etc.

I can do it recursively, like this:

def repeated(f, count):
   if count == 1:
   return f
   else:
   return lambda x: f(repeated(f, count - 1)(x)

But when I try to do it iteratively, it just hangs when I try to
evaluate the results (for count > 1):

def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x: newfun(f(x))
return newfun

For the life of me, I can't figure out why.  It seems like for count =
2, for example, the results from repeated2 should be lambda x: f(f(x)),
but it doesn't seem to be.

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


Re: Bug in email package?

2005-02-21 Thread Roman Suzi
On Sun, 20 Feb 2005, Steven Bethard wrote:
Erik Max Francis wrote:
Roman Suzi wrote:
I think that if any object (from standard library at least) doesn't support
iteration, it should clearly state so.
My guess is that 'for' causes the use of 'm[0]', which is (rightfully) an 
error...

Can this behaviour of email be considered a bug?
Is there a good case to iterate over something useful in a message
Why would it be a bug if the documentation never stated that the object was 
iterable?
I think the bug is not that an error is produced, but that the _wrong_ error 
is produced.  Trying to iterate over something that is not iterable should
Well, that was what I meant.
produce a TypeError saying so (not an Attribute error):
py> class C(object):
... pass
...
py> iter(C())
Traceback (most recent call last):
 File "", line 1, in ?
TypeError: iteration over non-sequence
I've actually seen something like this come up before (I think with 
email.Message even...)  I say call it a bug and submit a patch.
Ok. A bug minute on the next bug day ;-)
It's pretty 
easy to fix -- just add an __iter__ method to Message that raises a TypeError. 
That makes it clear that Message doesn't intend to support the getitem 
protocol -- it just does so accidentally because it provides __getitem__.

STeVe
Sincerely yours, Roman Suzi
--
[EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple index

2005-02-21 Thread Steve M
John Machin wrote:

> 
> Steve M wrote:
>> Hello,
>>
>> I'm trying to figure out the index position of a tuple
> member.
>> I know the member name, but I need to know the members index
> position.
> 
> Tuples, like lists, don't have members in the sense that they can be
> "named" like t.foo. The only way of referring to them is by index,
> t[4].
> 
>> I
>> know that if I use the statement print tuple[4] that it will print
> the
>> contents of that location. What I don't understand is if I know that
> foo is
>> a member of tuple, how do I get foo's index position.
> 
> You *can't* "know that foo is a member of tuple".
> 
> Consider this:
> 
 foo = 'carol'
 t = (123,456,789,'bob',foo,'ted')
 t[4]
> 'carol'
> 
> Is that what you mean by "foo is a member of t'? Well, it's not. foo is
> a reference to the string 'carol'. t[4] is also a reference to the
> string 'carol'.
> 
> Now read on ...
> 
 foo = 'alice'
 t
> (123, 456, 789, 'bob', 'carol', 'ted')
 t[4]
> 'carol'

> 
> Now foo is a reference to the string 'alice'. Nothing to do with t,
> either before or now.
> 
> Have you read the tutorial found at http://docs.python.org/tut/tut.html
> ?

I guess I explained my problem incorrectly. Let me try again.

tuple = ("fred", "barney", "foo")

I know that foo is an element of tuple, but what I need to know is what
the index of foo is, tuple[?]. Hopefully this explains what I'm trying 
do do better. Sorry about the earlier confusion.

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


Re: iterative lambda construction

2005-02-21 Thread Paul Rubin
"markscottwright" <[EMAIL PROTECTED]> writes:
> But when I try to do it iteratively, it just hangs when I try to
> evaluate the results (for count > 1):
> 
> def repeated2(f, count):
> newfun = f
> for i in range(count-1):
> newfun = lambda x: newfun(f(x))
> return newfun
> 
> For the life of me, I can't figure out why.  It seems like for count =
> 2, for example, the results from repeated2 should be lambda x: f(f(x)),
> but it doesn't seem to be.

It's Python's scoping madness.  Try:

  def repeated2(f, count):
 newfun = lambda x: x   # identity
 for i in range(count):
 newfun = lambda x, g=newfun: g(f(x))
 return newfun
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterative lambda construction

2005-02-21 Thread Andrew Koenig
"markscottwright" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Just for the hell of it, I've been going through the old Scheme-based
> textbook "Structure and Interpretation of Computer Programs" and seeing
> what I can and can't do with python.  I'm trying to create a function
> that returns the function (not the results of the function, but a
> function object) that results from applying function f to it's (single)
> argument N times.  For example, if you have "def sq(x): return x*x",
> then repeated(sq, 2)(2) = 16, repeated(sq, 3)(2) = 256, etc.
>
> I can do it recursively, like this:
>
> def repeated(f, count):
>   if count == 1:
>   return f
>   else:
>   return lambda x: f(repeated(f, count - 1)(x)
>
> But when I try to do it iteratively, it just hangs when I try to
> evaluate the results (for count > 1):
>
> def repeated2(f, count):
>newfun = f
>for i in range(count-1):
>newfun = lambda x: newfun(f(x))
>return newfun

The trouble is that Python's scoping rules are subtly different from 
Schemes, so you're binding to the wrong instance of newfun.  You should do 
this:

def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x, g=newfun: g(f(x))
return newfun

Alternatively, you could do it this way:

def repeated3(f, count):
def g(x):
for i in range(count):
x = f(x)
return x
return g


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


Re: Don't understand global variables between modules

2005-02-21 Thread Terry Reedy

"Bart" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I don't understand globals between multiple modules in a python program.

Because there are not any.  All names are bound to objects in a module 
global namespace, a function local namespace, or an object attribute 
namespace.

The builtins seem like and act like intermodule 'globals', but their names 
are bound in a hidden module which is imported to all other modules and 
treated like an extension of each module's namespace.  Users can do 
something similar by defining a 'myglobals' module and importing it 
everywhere.

> I've narrowed it down to the following two very simple
> programs a.py and b.py. When I run a.py I get the following output:
>
> inc:  2
> A:  2
> inc:  3
> B:  3
> C:  1
> I don't understand the last line at all.

Don't feel too bad.  While I 'know' the answer -- running anyfile.py 
creates a module named '__main__' while importing it (in another module) 
creates a separate module named 'anyfile' -- it did not 'click' until 
reading Fredrik's hint.  You created a nice, memorable example that shows 
that __main__ is not anotherfile.anyfile (in this case, not b.a)!

Terry J. Reedy



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


Re: iterative lambda construction

2005-02-21 Thread Steven Bethard
markscottwright wrote:
Just for the hell of it, I've been going through the old Scheme-based
textbook "Structure and Interpretation of Computer Programs" and seeing
what I can and can't do with python.  I'm trying to create a function
that returns the function (not the results of the function, but a
function object) that results from applying function f to it's (single)
argument N times.  For example, if you have "def sq(x): return x*x",
then repeated(sq, 2)(2) = 16, repeated(sq, 3)(2) = 256, etc.
I can do it recursively, like this:
def repeated(f, count):
   if count == 1:
   return f
   else:
   return lambda x: f(repeated(f, count - 1)(x)
But when I try to do it iteratively, it just hangs when I try to
evaluate the results (for count > 1):
def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x: newfun(f(x))
return newfun
For the life of me, I can't figure out why.
Your problem is that lambdas (and defs) do late-binding.  Consider the 
following code:

py> newfun = (1).__add__
py> id(newfun)
18354384
py> newfun = lambda: sys.stdout.write('%s' % id(newfun))
py> id(newfun)
18217328
py> newfun()
18217328
Note that the id of 'newfun' is the same in the body of the lambda as 
the id of 'newfun' after the lambda is defined.  That is, if 'newfun' in 
the lambda were to be called, it would call the lambda function 
recursively, instead of calling the previous 'newfun'.  This is why 
you're getting infinite recursion.

The reason this happens is that, when a name is not bound by the 
argument list of a function, Python will look for that name in the 
enclosing scopes.  Since the lambda does not bind the name 'newfun', 
Python looks out to the enclosing scope to find 'newfun' (which, in this 
case, happens to be the funciton itself).

One solution to this problem is to bind the old function to a name in 
the argument list of your lambda[1]:

py> def repeated2(f, count):
... newfun = f
... for i in range(count - 1):
... def newfun(x, oldfun=newfun):
... return oldfun(f(x))
... return newfun
...
py> def square(x):
... return x**2
...
py> repeated2(square, 2)(2)
16
py> repeated2(square, 3)(2)
256
Another possibility would be to store the old function as part of a 
class instance:

py> class Composer(object):
... def __init__(self, outerfunc, innerfunc):
... self.outerfunc = outerfunc
... self.innerfunc = innerfunc
... def __call__(self, x):
... return self.outerfunc(self.innerfunc(x))
...
py> def repeated2(f, count):
... newfun = f
... for _ in range(count - 1):
... newfun = Composer(newfun, f)
... return newfun
...
py> repeated2(square, 2)(2)
16
py> repeated2(square, 3)(2)
256
Note that either way, you need some means to store the old value of 
newfunc.  In the first case, it's stored by binding it as a default 
value of one of the the function's arguments.  In the second case, it's 
stored as an instance attribute of a class.

STeVe
[1] I use def instead of lambda.  See "Inappropriate use of Lambda" in 
http://www.python.org/moin/DubiousPython
--
http://mail.python.org/mailman/listinfo/python-list


Re: iterative lambda construction

2005-02-21 Thread Jack Diederich
On Mon, Feb 21, 2005 at 01:14:00PM -0800, Paul Rubin wrote:
> "markscottwright" <[EMAIL PROTECTED]> writes:
> > But when I try to do it iteratively, it just hangs when I try to
> > evaluate the results (for count > 1):
> > 
> > def repeated2(f, count):
> > newfun = f
> > for i in range(count-1):
> > newfun = lambda x: newfun(f(x))
> > return newfun
> > 
> > For the life of me, I can't figure out why.  It seems like for count =
> > 2, for example, the results from repeated2 should be lambda x: f(f(x)),
> > but it doesn't seem to be.
> 
> It's Python's scoping madness.  Try:
> 
>   def repeated2(f, count):
>  newfun = lambda x: x   # identity
>  for i in range(count):
>  newfun = lambda x, g=newfun: g(f(x))
>  return newfun

Ahh, but not sufficienty evil or pernicious.

def evil(f, count):
  def apply_evil(accum, func):
  return func(accum)
  def pernicious(x):
return reduce(apply_evil, [f]*count, x)
  return pernicious

def f(x):
return x+x

print evil(f, 3)(2)

More seriously I'd go without the recursion and just make a wrapper
that applies the function count times in a wrapper.

def benign(f, count):
  def wrap(x):
result = f(x)
for (i) in range(count-1):
  result = f(result)
return result
  return wrap

print benign(f, 3)(2)

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


Re: Tuple index

2005-02-21 Thread Michael Hartl
I actually find it strange that tuples don't have an index function,
since finding the index doesn't involve any mutation.  Anyone know why
Python doesn't allow a statement like t.index('foo')?

In any case, you can use the index method of list objects if you
convert your tuple to a list first:

>>> t = ("fred", "barney", "foo")
>>> list(t).index("foo")
2
>>> def index(a_tuple, element):
... return list(a_tuple).index(element)
...
>>> t[index(t, "foo")]
'foo'

(By the way, 'tuple' is a Python built-in type, so it's probably best
to avoid using it as a variable name.)


Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

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


Re: Tuple index

2005-02-21 Thread Steven Bethard
Steve M wrote:
I guess I explained my problem incorrectly. Let me try again.
tuple = ("fred", "barney", "foo")
I know that foo is an element of tuple, but what I need to know is what
the index of foo is, tuple[?].
Larry Bates's solution is probably the best way to go here:
py> t = ("fred", "barney", "foo")
py> list(t).index("foo")
2
py> t[2]
'foo'
But note that if you're doing this often, you're probably using tuple 
for the wrong things.  Check out:

http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types
If you're iterating over the items of something and the items are all of 
 the same type, you probably want a list, not a tuple.

What's the use case in which you want to do this?
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >