ANN: python-constraint 1.0

2005-07-06 Thread Gustavo Niemeyer

Overview


**python-constraint** [1]_ is a Python module offering solvers for
Constraint Solving Problems (CSPs) over finite domains in simple
and pure Python. CSP is class of problems which may be represented
in terms of variables (`a`, `b`, ...), domains (`a in [1, 2, 3]`, ...),
and constraints (`a < b`, ...).

.. [1] http://codespeak.net/~niemeyer/constraint/


Examples


Basic
-

Here is a basic interactive example::
 
>>> from constraint import *
>>> problem = Problem()
>>> problem.addVariable("a", [1,2,3])
>>> problem.addVariable("b", [4,5,6])
>>> problem.getSolutions()
[{'a': 3, 'b': 6}, {'a': 3, 'b': 5}, {'a': 3, 'b': 4},
 {'a': 2, 'b': 6}, {'a': 2, 'b': 5}, {'a': 2, 'b': 4},
 {'a': 1, 'b': 6}, {'a': 1, 'b': 5}, {'a': 1, 'b': 4}]

>>> problem.addConstraint(lambda a, b: a*2 == b,
  ("a", "b"))
>>> problem.getSolutions()
[{'a': 3, 'b': 6}, {'a': 2, 'b': 4}]

>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> problem.addConstraint(AllDifferentConstraint())
>>> problem.getSolutions()
[{'a': 3, 'b': 2}, {'a': 3, 'b': 1}, {'a': 2, 'b': 3},
 {'a': 2, 'b': 1}, {'a': 1, 'b': 2}, {'a': 1, 'b': 3}]


Rooks
-

Here is an example solving the classical rooks problem::

problem = Problem()
numpieces = 8
cols = range(numpieces)
rows = range(numpieces)
problem.addVariables(cols, rows)
for col1 in cols:
for col2 in cols:
if col1 < col2:
problem.addConstraint(lambda row1, row2: row1 != row2,
  (col1, col2))
solutions = problem.getSolutions()


Magic squares
-

And here is an example solving a 4x4 magic square::

problem = Problem()
problem.addVariables(range(0, 16), range(1, 16+1))
problem.addConstraint(AllDifferentConstraint(), range(0, 16))
problem.addConstraint(ExactSumConstraint(34), [0,5,10,15])
problem.addConstraint(ExactSumConstraint(34), [3,6,9,12])
for row in range(4):
problem.addConstraint(ExactSumConstraint(34),
  [row*4+i for i in range(4)])
for col in range(4):
problem.addConstraint(ExactSumConstraint(34),
  [col+4*i for i in range(4)])
solutions = problem.getSolutions()



Features


The following solvers are available:

- Backtracking solver
- Recursive backtracking solver
- Minimum conflicts solver

Predefined constraint types currently available:

- FunctionConstraint
- AllDifferentConstraint
- AllEqualConstraint
- ExactSumConstraint
- MaxSumConstraint
- MinSumConstraint
- InSetConstraint
- NotInSetConstraint
- SomeInSetConstraint
- SomeNotInSetConstraint


-
Documentation
-

There's documentation for the module at:

- http://codespeak.net/~niemeyer/constraint/doc/



Download


**python-constraint** may be found at the following
address:

- http://codespeak.net/~niemeyer/constraint/files/

-
Subversion repository
-

Available at:

- http://codespeak.net/svn/user/niemeyer/constraint/


-- 
Gustavo Niemeyer
http://niemeyer.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Reinhold Birkenfeld
Ron Adam wrote:

> Given the statement:
> 
> a = None
> 
> And the following are all true:
> 
>   a == None

Okay.

> (a) == (None)

Okay.

> (a) == ()

Whoops! a (which is None) is equal to the empty tuple (which is not None)?

> (None) == ()
>
> Then this "conceptual" comparison should also be true:
> 
> if (None):  ==  if ():
> if (): == if:

I can't really see any coherent concept here.

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Ron Adam
Mike Meyer wrote:

> Ron Adam <[EMAIL PROTECTED]> writes:
> 
>>So doing this would give an error for functions that require an argument.
>>
>> def foo(x):
>> return x
>>
>> a = None
>> b = foo(a)#  error because a dissapears before foo gets it.
> 
> 
> So how do I pass None to a function?

You wouldn't.  What would a function do with it anyway?  If you wanted 
to pass a neutral value of some sort, then you'd just have to pick 
something else and test for it.  Maybe we could use Nil as an 
alternative to None for that purpose?


>>6.  x = foo()#  Would give an error if foo returns None
> 
> Why? Shouldn't it delete x?

That was my first thought as well.

It would cause all sorts of problems.  One way to avoid those is to 
insist that the only way to assign (delete) a name to None is by 
literally using "None" and only "None" on the right side of the = sign.

Any undefined name on the right side would give an error except for None 
itself.

>>This might be an improvement over current behavior.  Breaks a lot of
>>current code though.
>  
> I don't think so. I've programmed in langauges that gave undefined
> variables a value rather than an exception. It almost inevitabley led
> to hard-to-find bugs.

That is why the above should give an error I believe.  ;)


> FORTRAN used to give all variables a type, so that a typo in a
> variable name could well lead to a valid expression. The technic for
> disabling this was baroque ("IMPLICIT BOOLEAN*1 A-Z"), but so common
> they invented a syntax for it in later versions of FORTRAN ("IMPLICIT
> NONE").

It's been so long since I did anything if Fortran I've actual don't 
recall any of it.  :)  '83-'84

I went from that to pascal, which I thought was a big improvement at the 
time.

Cheers,
Ron

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


Re: Lisp development with macros faster than Python development?..

2005-07-06 Thread Philippe C. Martin


Almost sounds like a racist comment - sorry if I misunderstood


Antoon Pardon wrote:

> Op 2005-07-06, Michele Simionato schreef <[EMAIL PROTECTED]>:
>> Fuzzyman:
>>> So Lisp is for really good programmers, and Python is for
>>> mediocre programmers ?
>>
>>
>> Python is *also* for mediocre programmers. I see this as a
>> strength, not as a weakness.
> 
> But sometimes I get the impression people want it to evolve
> so it is only for mediocre programmers.
> 

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


Re: Python exception hook simple example needed

2005-07-06 Thread Ed Leafe
On Jul 6, 2005, at 8:59 AM, Fuzzyman wrote:

> Wax has a brilliant prebuilt dialog/handler. It's a wrapper over
> wxPython - so you still use wxPython objects, it's jsut all a lot
> easier.

And don't forget Dabo, which wraps all of wxPython's dialogs into 
simple calls. No need to create/show/destroy; just call the appropriate 
function.

I know I'm biased, being one of the authors, but I've used both 
extensively, and find Dabo so much easier to work with. And if there's 
a part of wxPython that we haven't wrapped yet, let us know, as we are 
actively working on Dabo and improving it all the time.

  ___/
 /
__/
   /
  /
  Ed Leafe
  http://leafe.com/
  http://dabodev.com/

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


Re: Use cases for del

2005-07-06 Thread Ron Adam
Grant Edwards wrote:

> On 2005-07-07, Ron Adam <[EMAIL PROTECTED]> wrote:
> 
>>Grant Edwards wrote:
>>
>>
>>>On 2005-07-06, Ron Adam <[EMAIL PROTECTED]> wrote:
>>>
>>>
>>>
It would be a way to set an argument as being optional without
actually assigning a value to it.  The conflict would be if
there where a global with the name baz as well.  Probably it
would be better to use a valid null value for what ever baz if
for.  If it's a string then "", if its a number then 0, if it's
a list then [], etc...
>>>
>>>Except those aren't "null values" for those types.  0 is a
>>>perfectly good integer value, and I use it quite often. There's
>>>a big difference between an "invalid integer value" and an
>>>integer with value 0.
>>
>>Why would you want to use None as an integer value?
> 
> 
> 1) So I know whether an parameter was passed in or not. Perhaps
>it's not considered good Pythonic style, but I like to use a
>single method for both get and set operations.  With no
>parameters, it's a get.  With a parameter, it's a set:
> 
>class demo:
>   def foo(v=None):
>   if v is not None:
>   self.v = v
>   return self.v   

You are really checking if v exists, so having it undefined in namespace 
  as the default is consistent with what you are doing.

As I said above...

 It would be a way to set an argument as being optional without
 actually assigning a value to it.

So it would still work like you expect even though v is not bound to 
anything.  Like I said the bigger problem is that globals will be 
visible and that would create a conflict.  Setting a value to None in a 
function hides globals of the same name.  That wouldn't happen if None 
unbound names as del does.

So you would need to use something else for that purpose I suppose, but 
that was why None became a literal in the first place, so maybe it's 
taking a step backwards.


> 2) So I can use it as sort of a NaN equivalent.
> 
>if self.fd is None:
>   self.fd = os.open('foo.bar','w')
>
>if self.fd is not None:
>   os.close(self.fd)
>   self.fd = None  

It would still work as you expect.  A while back I suggested an 'also' 
for if that would do exactly that with only one test.  Nobody liked it.

  if self.fd is None:
 self.fd = os.open('foo.bar','w')
 # do something with self.fd

  also:
 os.close(self.fd)
 self.fd = None


>>If a value isn't established yet, then do you need the name
>>defined?
>  
> I find it more obvious to set the name to None during the
> periods that it isn't valid than to delete it and check for a
> NameError when I want to know if the value is usable or not.

You would still be able to do that explicitly and it probably would be a 
good idea when you aren't sure if a name is left over from something else.

If a name is None, it means it's available and unassigned, so you don't 
have to check for a NameError.


>>Wouldn't it be better to wait until you need the name then
>>give it a value?
> 
> "Better" is a value judgement.  I prefer setting it None and
> than deleting it and then checking for existance.

They would be the same in this case.  Setting it to None would delete it 
also.  And checking it for None will let you know it's available or if 
it has a value...

You are right that it's a value judgment.  I agree.  BTW, I'm sort of 
just exploring this a bit, not trying to argue it's any better than what 
we currently do.  I think it could work either way, but it would mean 
doing things in a different way also, not neccisarily a good idea.

Cheers,
Ron


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


Re: I am a Java Programmer

2005-07-06 Thread godwin
Buy the book "Practical Python" by Magnus Lie Hetland. It contains 10
practical projects to let u get started on you own "Pythoneering"( as
Magnus calls it). Move on buddy.

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


Re: Lisp development with macros faster than Python development?..

2005-07-06 Thread Gregory Bond
Rocco Moretti wrote:

> Actually, Google's answer to that question is something called "ILOG 
> CPLEX", 

We use this.  It's a library / command line tool (not a language) for 
doing optimization - linear programming, quadratic programming, 
mixed-integer programming etc.  Very cool and very, very scarey.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-06 Thread Grant Edwards
On 2005-07-07, Leif K-Brooks <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
>> On 2005-07-07, Leif K-Brooks <[EMAIL PROTECTED]> wrote:
>>>_NOVALUE = object()
>>>class demo:
>>>def foo(v=_NOVALUE):
>>>if v is _NOVALUE:
>>>return self.v
>>>else:
>>>self.v = v
>> 
>> 
>> Apart from the change in the logic such that the set operation
>> doesn't return a value, how is that any different?  You're just
>> creating your own non-integer-value "None" object instead of
>> using the one built in to the language.
>
> Sorry, my mistake: for some reason, I misunderstood your message as
> complaining that you couldn't do the same thing if you needed None to be
> usable as a value too.

Somebody had proposed eliminating None as a usable object and
people who use None now should just use 0, [], "", or ()
depending on the "type" of the expected value.  I was providing
an example of where I would use None in a context where an
"integer context" and where 0 wasn't a good substitue.

>>>But what's wrong with properties?
>> 
>> Huh?
>
> Why not use a property
> (http://www.python.org/2.2.1/descrintro.html#property) instead of a
> special property-like method?

Habit and the desire to make it explicit that something more is
going on that just assigning or evaluating an instance's
attribute.

-- 
Grant Edwards   grante Yow!  I want EARS! I
  at   want two ROUND BLACK
   visi.comEARS to make me feel warm
   'n secure!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-06 Thread Grant Edwards
On 2005-07-07, George Sakkis <[EMAIL PROTECTED]> wrote:

> I guess he means why not define foo as property:
>
> class demo(object):
> foo = property(fget = lambda self: self.v,
>fset = lambda self,v: setattr(self,'v',v))
>
> d = demo()
> d.foo = 3
> print d.foo

In some ways that's even cleaner.

In my simplivied example all the foo() method was doing was
setting/returning an attribute, but usually there's a bit more
going on (e.g. system calls with possible side effects).  

To me it's a bit more explicit that

  d.foo(3)
  d.foo()

are doing something other than just getting/setting the value
of an instance attribute.  If all I really wanted to do was
get/set the instance's "v" attribute, I probably would have
just done it like this

  d.v = 3
  print d.v  

-- 
Grant Edwards   grante Yow!  .. I wonder if I
  at   ought to tell them about my
   visi.comPREVIOUS LIFE as a COMPLETE
   STRANGER?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there an equivalent of javascript's this["myMethod"] for the currently running script?

2005-07-06 Thread markturansky
getattr does not work on a running script (afaik) because 'self' is
undefined.  The poster above got it right using 'locals()'

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


Re: is there an equivalent of javascript's this["myMethod"] for the currently running script?

2005-07-06 Thread markturansky
'self' is not defined in this circumstance.  The poster above (using
'locals()') has it right.

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


Re: is there an equivalent of javascript's this["myMethod"] for the currently running script?

2005-07-06 Thread markturansky
Yes, that is exactly what I was looking for.  Thank you.  I will read
more about 'locals()', but a quick test proved you right.

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


Re: Use cases for del

2005-07-06 Thread Leif K-Brooks
Grant Edwards wrote:
> On 2005-07-07, Leif K-Brooks <[EMAIL PROTECTED]> wrote:
>>_NOVALUE = object()
>>class demo:
>>def foo(v=_NOVALUE):
>>if v is _NOVALUE:
>>return self.v
>>else:
>>self.v = v
> 
> 
> Apart from the change in the logic such that the set operation
> doesn't return a value, how is that any different?  You're just
> creating your own non-integer-value "None" object instead of
> using the one built in to the language.

Sorry, my mistake: for some reason, I misunderstood your message as
complaining that you couldn't do the same thing if you needed None to be
usable as a value too.

>>But what's wrong with properties?
> 
> Huh?

Why not use a property
(http://www.python.org/2.2.1/descrintro.html#property) instead of a
special property-like method?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flatten(), [was Re: map/filter/reduce/lambda opinions ...]

2005-07-06 Thread Ron Adam
Stian Søiland wrote:

> Or what about a recursive generator?
> 
> a = [1,2,[[3,4],5,6],7,8,[9],[],]
> 
> def flatten(item):
> try:
> iterable = iter(item)
> except TypeError:
> yield item  # inner/final clause
> else:
> for elem in iterable:
> # yield_return flatten(elem)
> for x in flatten(elem):
> yield x
> 
> print list(flatten(a))


Ok,  lets see...  I found a few problems with the testing (and corrected 
it)  so the scores have changed.   My sort in place routines were 
cheating because the lists weren't reset between runs so it had the 
advantage after the first time though of sorting already sorted list. 
And Tom's recursive no copy had a bug which kept a reference to one of 
it's arguments so it's output was doubling the list.  And the hasattr 
function was slowing everyone down, so I inlined it for everyone who 
used it.

Using a 1000 item list and starting with a flat list and increasing the 
depth (unflatten) to shallow, medium, and deep.  (but not so deep to 
cause recursion errors.)

And the winners are...



Python 2.3.5 (#62, Feb  8 2005, 16:23:02)
[MSC v.1200 32 bit (Intel)] on win32
IDLE 1.0.5

 >>>

Size: 1000   Depth: 0
georges_recursive_flatten:   0.00212513042834
rons_nonrecursive_flatten:   0.00394323859609
toms_recursive_zerocopy_flatten: 0.00254557492644
toms_iterative_zerocopy_flatten: 0.0024332701505
devans_smallest_recursive_flatten:   0.011406198274
rons_nonrecursive_inplace_flatten:   0.00149963193644
stians_flatten_generator:0.00798257879114

Size: 1000   Depth: 25
georges_recursive_flatten:   0.0639824335217
rons_nonrecursive_flatten:   0.0853463219487
toms_recursive_zerocopy_flatten: 0.0471856059917
toms_iterative_zerocopy_flatten: 0.188437915992
devans_smallest_recursive_flatten:   0.0844073757976
rons_nonrecursive_inplace_flatten:   0.0847048996452
stians_flatten_generator:0.0495694285169

Size: 1000   Depth: 50
georges_recursive_flatten:   0.134300309118
rons_nonrecursive_flatten:   0.183646245542
toms_recursive_zerocopy_flatten: 0.0886252303017
toms_iterative_zerocopy_flatten: 0.371141304272
devans_smallest_recursive_flatten:   0.185467985456
rons_nonrecursive_inplace_flatten:   0.188668392212
stians_flatten_generator:0.090114246364

Size: 1000   Depth: 100
georges_recursive_flatten:   0.248168133101
rons_nonrecursive_flatten:   0.380992276951
toms_recursive_zerocopy_flatten: 0.177362486014
toms_iterative_zerocopy_flatten: 0.741958265645
devans_smallest_recursive_flatten:   0.306604051632
rons_nonrecursive_inplace_flatten:   0.393641091256
stians_flatten_generator:0.177185368532
 >>>


Stians flatten generator is nearly tied with Tom's recursive zerocopy. 
My nonrecursive inplace is faster for very shallow lists, but Tom's 
quickly over takes it.  I was able to improve my nonrecursive copy 
flatten a bit, but not enough to matter.  So Tom's recursive zerocopy is 
the overall winner with Stian's flatten generator close behind and just 
barely winning out in the very deep catagory.  But they're all 
respectable times so everyone wins. ;-)



And here's the source code.

Cheers,  :-)
Ron



# ---

import sys
import time

TIMERS = {"win32": time.clock}
timer = TIMERS.get(sys.platform, time.time)

def timeit(fn,*arg):
 t0 = timer()
 r = fn(*arg)
 t1 = timer()
 return float(t1-t0), r

# 

def georges_recursive_flatten(seq):
 return reduce(_accum, seq, [])

def _accum(a, item):
 if hasattr(item, "__iter__"):
 a.extend(georges_recursive_flatten(item))
 else:
 a.append(item)
 return a


def rons_nonrecursive_flatten(seq):
 a = []
 while seq:
 if hasattr(seq[0], "__iter__"):
 seq[0:1] = seq[0]
 else:
 a.append(seq.pop(0))
 return a


def toms_recursive_zerocopy_flatten(seq, a=None):  #a=[] kept a 
reference to a?
 if a==None:
 a = []
 if hasattr(seq,"__iter__"):
 for item in seq:
 toms_recursive_zerocopy_flatten(item, a)
 else:
 a.append(seq)
 return a


def toms_iterative_zerocopy_flatten(seq):
 stack = [None]
 cur = iter(seq)
 a = []
 while (cur != None):
 try:
 item = cur.next()
 if hasattr(item,"__iter__"):
 stack.append(cur)
 cur = iter(item)
 else:
 a.append(item)
 except StopIteration:
 cur = stack.pop()
 return a


def devans_smallest_recursive_flatten(seq):
 if hasattr(seq,"__iter__"):
 return sum([devans_smallest_recursive_flatten(item) for item in 
seq], [])
 else:
 return [seq]


def rons_nonrecursive_inplace_flatten(seq):
 i = 0
 while 

Re: Favorite non-python language trick?

2005-07-06 Thread Mike Meyer
"Shai" <[EMAIL PROTECTED]> writes:

> They're called "Special vars", and you need to define them (unlike
> local LISP variables, which behave essentially like Python vars), but
> then you use them just like other vars (that is, you usually bind them
> with LET). This is the first I hear about them being ill-considered in
> LISP; http://www.gigamonkeys.com/book/ is a recently published LISP
> book which recommends them. I don't know about Scheme, but I think it
> does have them.

I'm pretty sure scheme doesn't have dynamically bound variables. I
just went through r5rs to check, and couldn't find them.

> dynamic x=10
> def bar():
>   print x
>
> I specified the syntax as I did, specifically to make it match the
> current definition of globals, which "enjoys" the same problems you
> noted with my dynamics.

This looks different from what I understood before. You're now
declaring the variable dynamic in the global scope, rather than in the
function that makes it dynamic. This is a *much* more palatable
situation.

Globals are lexically scoped. As such, you can find the defintion of
the variable by examining the module that includes the function. Yes,
other modules can reach into your module and change them - but you can
find those, because they reference your module by name.

A dynamic variable declared so in a function has no such clue
associated with it. If the variable is declared dynamic in the module
of the enclosed function, that provides a contextual clue.

Of course, you can do pretty much anything you want if you're willing
to grovel over the guts of the environment enough, but some things
shouldn't be easy.

> While I didn't write it explicitly, if both LISP and Python globals are
> to be followed, the dynamic x should somehow be defined in the scope of
> its module. On second thought, this means "dynamic" _must_ be added in
> the variable definition, for foo.foogle will simply access it as
> "othermodule.x", which doesn't differentiate globals from dynamics.
>
> Either way, Python as it is now allows foo.foogle to change x even
> without dynamic variables; it is accessible as barmodule.x. bar()
> should expect to have other functions mess with its globals, and
> dynamics are no different.

The question is, how hard is it to find the other people who are
messing with bar()'s globals? Normal usage with the current situation
makes it fairly starightforward. How does adding dynamicly bound
variables change this?

Of course, if you add the requirement that the variable be tagged in
the scope of the module, you're making things a lot better. That way,
readers of the module know that they need to look back along the call
chain for functions that use such variables. That makes them much
saner to find.

>> Instead of dynamic meaning "all references to the named variable(s)
>> will be dynamic until this function exits", have it mean "the named
>> variable(s) will be dynamic in this function." Whether it should only
>> check local variables in the calling routines, check local + global,
>> or check for all free variables, is an open question.
>>
>> I.e. - your example would be written:
>>
>> x = 10
>> def foo():
>> dynamic x
>> print x
>>
>> def bar():
>> x = 11
>> foo()
>>
>> def baz():
>> bar()   # prints 11
>> foo()   # Possibly an error?
>>
>
> This introduces the same problem you noted with my original proposal,
> but in reverse: Now, in bar(), you define and use a local variable, and
> suddenly some library function changes its behavior misteriously.

True. That pretty much kills my proposal.

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


Re: Use cases for del

2005-07-06 Thread George Sakkis
"Grant Edwards" wrote:

> In 2005-07-07, Leif K-Brooks <[EMAIL PROTECTED]> wrote:
>
> - Hide quoted text -
> - Show quoted text -
> > Grant Edwards wrote:
> >> 1) So I know whether an parameter was passed in or not. Perhaps
> >>it's not considered good Pythonic style, but I like to use a
> >>single method for both get and set operations.  With no
> >>parameters, it's a get.  With a parameter, it's a set:
>
> >>class demo:
> >>   def foo(v=None):
> >>   if v is not None:
> >>   self.v = v
> >>   return self.v
>
> > _NOVALUE = object()
> > class demo:
> > def foo(v=_NOVALUE):
> > if v is _NOVALUE:
> > return self.v
> > else:
> > self.v = v
>
> Apart from the change in the logic such that the set operation
> doesn't return a value, how is that any different?  You're just
> creating your own non-integer-value "None" object instead of
> using the one built in to the language.
>
> > But what's wrong with properties?
>
> Huh?

I guess he means why not define foo as property:

class demo(object):
foo = property(fget = lambda self: self.v,
   fset = lambda self,v: setattr(self,'v',v))

d = demo()
d.foo = 3
print d.foo


George

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


Re: Use cases for del

2005-07-06 Thread Grant Edwards
On 2005-07-07, Leif K-Brooks <[EMAIL PROTECTED]> wrote:

> Grant Edwards wrote:
>> 1) So I know whether an parameter was passed in or not. Perhaps
>>it's not considered good Pythonic style, but I like to use a
>>single method for both get and set operations.  With no
>>parameters, it's a get.  With a parameter, it's a set:
>> 
>>class demo:
>>   def foo(v=None):
>>   if v is not None:
>>   self.v = v
>>   return self.v  
>
> _NOVALUE = object()
> class demo:
> def foo(v=_NOVALUE):
> if v is _NOVALUE:
> return self.v
> else:
> self.v = v

Apart from the change in the logic such that the set operation
doesn't return a value, how is that any different?  You're just
creating your own non-integer-value "None" object instead of
using the one built in to the language.

> But what's wrong with properties?

Huh?

-- 
Grant Edwards   grante Yow!
  at   TAILFINS!!... click...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Mike Meyer
Ron Adam <[EMAIL PROTECTED]> writes:
> So doing this would give an error for functions that require an argument.
>
>  def foo(x):
>  return x
>
>  a = None
>  b = foo(a)#  error because a dissapears before foo gets it.

So how do I pass None to a function?

>  >>TypeError: foo() takes exactly 1 argument(0 given)
>
>
> So they wouldn't propagate like you would expect.
>
> Hmmm interesting that would mean... lets see.
>
>
> 1. var = None# removes ref var,  this is ok
>
> 2. None = var# give an error of course
>
> 3. var = undefined_var   # same as "var = None",  that's a problem!
>
> Ok... this must give an error because it would delete var silently!
> Definitely not good.  So going on, on that basis.
>
> 4. undefined == None # Special case, evaluates to True.
>
> 5.  def foo():return None   # same as return without args
>
> 6.  x = foo()#  Would give an error if foo returns None

Why? Shouldn't it delete x?

> This might be an improvement over current behavior.  Breaks a lot of
> current code though.

I don't think so. I've programmed in langauges that gave undefined
variables a value rather than an exception. It almost inevitabley led
to hard-to-find bugs.

FORTRAN used to give all variables a type, so that a typo in a
variable name could well lead to a valid expression. The technic for
disabling this was baroque ("IMPLICIT BOOLEAN*1 A-Z"), but so common
they invented a syntax for it in later versions of FORTRAN ("IMPLICIT
NONE").

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


Re: Use cases for del

2005-07-06 Thread Leif K-Brooks
Grant Edwards wrote:
> 1) So I know whether an parameter was passed in or not. Perhaps
>it's not considered good Pythonic style, but I like to use a
>single method for both get and set operations.  With no
>parameters, it's a get.  With a parameter, it's a set:
> 
>class demo:
>   def foo(v=None):
>   if v is not None:
>   self.v = v
>   return self.v  

_NOVALUE = object()
class demo:
def foo(v=_NOVALUE):
if v is _NOVALUE:
return self.v
else:
self.v = v

But what's wrong with properties?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Considering moving from Delphi to Python [Some questions]

2005-07-06 Thread malkarouri
Dark Cowherd wrote:
> Stupid of me.
>
> I want some feedback on folllwing:
> anybody who has experience in writing SOAP servers in Python and data
> entry heavy web applications.
> Any suggestions?
> darkcowherd

Check ZSI, or SOAPPY, both on Python Web Services
http://pywebsvcs.sourceforge.net/
I usually use ZSI. You cannot generate wsdl files from python code, so
if I were in your shoes I would write the Delphi side and generate the
wsdl file then use it in python.

I never tested interoperability of Delphi & ZSI by the way, though I
would love to. Please inform us if you do try it.

btw, elementtree has an attempt at elementsoap but i don't think they
went very far..

cheers,
k

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


Re: I am a Java Programmer

2005-07-06 Thread Philippe C. Martin
I see you got many good/funny answers already.

Test Python for two WE and you'll be able to help yourself very well ...
I've been through an equivalent process.

Regards,

Philippe




[EMAIL PROTECTED] wrote:

> I am a java programmer and I want to learn Python Please help me.

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


Re: Compatibility of recent GCC/Python versions

2005-07-06 Thread Ralf W. Grosse-Kunstleve
--- David Abrahams <[EMAIL PROTECTED]> wrote:
> Recently people testing Boost.Python with GCC on Linux have reported
> that the extensions being tested have to be compiled with exactly the
> same version of GCC as the Python they're being loaded into, or they
> get mysterious crashes.
> 
> That doesn't correspond to my past experience; it has always been true
> that, as long as the compiler used to build Python and the one used to
> build the extension have compatible 'C' ABIs, we've been okay.  Yes,
> if you were going to pass types like FILE* across the Python/C API,
> then you additionally need to be sure that the two compilers are using
> the same 'C' library.  That said, none of the Boost.Python tests do
> that.
> 
> I'm wondering if there has been a well-known recent change either in Python
> or GCC that would account for these new reports.  Any relevant
> information would be appreciated.

Maybe the problems are due to libstdc++ incompatibilities?
See my other message:

http://lists.boost.org/boost/2005/07/29883.php

Cheers,
Ralf




__ 
Yahoo! Mail 
Stay connected, organized, and protected. Take the tour: 
http://tour.mail.yahoo.com/mailtour.html 

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


Re: Use cases for del

2005-07-06 Thread Grant Edwards
On 2005-07-07, Ron Adam <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
>
>> On 2005-07-06, Ron Adam <[EMAIL PROTECTED]> wrote:
>> 
>> 
>>>It would be a way to set an argument as being optional without
>>>actually assigning a value to it.  The conflict would be if
>>>there where a global with the name baz as well.  Probably it
>>>would be better to use a valid null value for what ever baz if
>>>for.  If it's a string then "", if its a number then 0, if it's
>>>a list then [], etc...
>> 
>> Except those aren't "null values" for those types.  0 is a
>> perfectly good integer value, and I use it quite often. There's
>> a big difference between an "invalid integer value" and an
>> integer with value 0.
>
> Why would you want to use None as an integer value?

1) So I know whether an parameter was passed in or not. Perhaps
   it's not considered good Pythonic style, but I like to use a
   single method for both get and set operations.  With no
   parameters, it's a get.  With a parameter, it's a set:

   class demo:
  def foo(v=None):
  if v is not None:
  self.v = v
  return self.v  

2) So I can use it as sort of a NaN equivalent.

   if self.fd is None:
  self.fd = os.open('foo.bar','w')
   
   if self.fd is not None:
  os.close(self.fd)
  self.fd = None  

> If a value isn't established yet, then do you need the name
> defined?

I find it more obvious to set the name to None during the
periods that it isn't valid than to delete it and check for a
NameError when I want to know if the value is usable or not.

> Wouldn't it be better to wait until you need the name then
> give it a value?

"Better" is a value judgement.  I prefer setting it None and
than deleting it and then checking for existance.

-- 
Grant Edwards   grante Yow!  Hey, LOOK!! A pair of
  at   SIZE 9 CAPRI PANTS!! They
   visi.comprobably belong to SAMMY
   DAVIS, JR.!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-06 Thread Ron Adam
Grant Edwards wrote:

> On 2005-07-06, Ron Adam <[EMAIL PROTECTED]> wrote:
> 
> 
>>It would be a way to set an argument as being optional without actually 
>>assigning a value to it.  The conflict would be if there where a global 
>>with the name baz as well.  Probably it would be better to use a valid 
>>null value for what ever baz if for.  If it's a string then "", if its a 
>>number then 0, if it's a list then [], etc...
> 
> 
> Except those aren't "null values" for those types.  0 is a
> perfectly good integer value, and I use it quite often. There's
> a big difference between an "invalid integer value" and an
> integer with value 0.

Why would you want to use None as an integer value?

If a value isn't established yet, then do you need the name defined? 
Wouldn't it be better to wait until you need the name then give it a value?



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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Ron Adam
Benji York wrote:
> Ron Adam wrote:
> 
>> "if extraargs:"  would evaluate to "if None:", which would evaluate to 
>> "if:" which would give you an error.
> 
> 
> In what way is "if None:" equivalent to "if:"?
> -- 
> Benji York

It's not now.. but if None where to really represent the concept None, 
as in not bound to anything, it would evaluate to nothing.

Given the statement:

a = None

And the following are all true:

  a == None
(a) == (None)
(a) == ()
(None) == ()

Then this "conceptual" comparison should also be true:

if (None):  ==  if ():
if (): == if:


Comparing if's like that wouldn't be a valid code of course, but it 
demonstrates the consistency in which the comparison is made.

I think. ;-)

Of course this is all hypothetical anyways, so it could be what ever we 
decide makes the most since, include not changing anything.

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


Re: Inheritance/Late Private Binding

2005-07-06 Thread Michael Hoffman
Jeremy Moles wrote:

> Forgive me if this topic has been brought up before, but I was curious
> as to why I was getting this behavior and was hoping someone
> knowledgeable could explain. :)

What behavior?

> I "feel" like even without the explicit call to a simple base ctor(),
> mangling should still happen correctly. This doesnt, however, seem to be
> the case...

How is mangling happening incorrectly?

Functions in base classes that are overridden by subclasses aren't 
called implicitly.

Also, I think using the term "ctor()" is confusing since you don't seem 
to have anything callable named ctor. As for the constructor, just call 
it __init__, it will avoid confusion with __new__.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Inheritance/Late Private Binding

2005-07-06 Thread Jeremy Moles
class BaseClass:
def __init__(self):
self.__data = None

def getMember(self):
return self.__data

class GoodSubClass(BaseClass):
def __init__(self):
BaseClass.__init__(self)

class BadSubClass(BaseClass):
def __init__(self):
self.__x = None

gsc = GoodSubClass()
print dir(gsc)
gsc.getMember()

bsc = BadSubClass()
print dir(bsc)
bsc.getMember()



Forgive me if this topic has been brought up before, but I was curious
as to why I was getting this behavior and was hoping someone
knowledgeable could explain. :)

I "feel" like even without the explicit call to a simple base ctor(),
mangling should still happen correctly. This doesnt, however, seem to be
the case...

Of note: simply doing a 'pass' in BadSubClass seems to be sufficient as
well; so, it has something to do with defining a ctor() in the child and
not explicitly invoking the parent's ctor.

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


Re: frozenset question

2005-07-06 Thread George Sakkis
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote:

> On Wed, 06 Jul 2005 10:15:31 -0700, George Sakkis wrote:
>
> > Well, they *may* be interchangable under some conditions, and that was
> > the OP's point you apparently missed.
>
> I didn't miss anything of the sort. That's why I spent 15 minutes actually
> producing test cases to MEASURE if there was any detectable speed
> differences between accessing set and frozenset instead of wasting time
> worrying about "tiny" differences in performance that are almost certainly
> lost in the noise in real code.
>
> If, over a thousand runs of the program, you save a millisecond of time in
> total, but it costs you two seconds to type the comment in the code
> explaining why you used frozenset instead of the more natural set, then
> your "optimization" is counter-productive. Even just considering the
> question is a waste of valuable developer time! THAT is the lesson of
> premature optimization: don't even THINK about optimizing code until you
> have it WORKING and you have MEASURED that it is too slow.

I fully agree with your last sentence, first profile and then consider
if it's worth optimizing. Still, you either missed the point again or
you are arguing for the sake of the argument. Neither me nor the OP
claimed that it's worthwhile saving a millisecond or two. The OP hadn't
done the timing measurements you did, so he didn't know in advance if
the difference is 1 millisecond or 500. After you replied with evidence
that it's not worth it, he made clear that he was just enquiring, not
optimizing prematurely as you took for granted and ranted against it
from the beginning.

Hope it's clear now,

George

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread David Abrahams
Bruno Desthuilliers <[EMAIL PROTECTED]> writes:

> I discovered FP with David Mertz's papers about FP in Python. I had 
> never read nor write a line of lisp, scheme, haskell, caml etc before. 
> And I'd certainly start thinking of choosing another MYFL if anonymous 
> functions where to disappear from Python. Note that I said "anonymous 
> functions", not "lambda". Concerning map, filter, reduce etc, these 
> functions can live in a separate module, and this wouldn't bother me. 
> But anonymous functions are part of the language syntax, so there is no 
> work-around.

Actually I'm pretty sure there is.  It should be possible to
re-implement the Boost Lambda library in Python:

   http://www.boost.org/libs/lambda

Compared with in-language lambda support it would have the advantage
of brevity and clarity for very small functions, but there are lots of
disadvantages, too.  I wonder how Guido would feel if people started
using a (relatively) slow library solution with odd warts as a
consequence of dropping real lambdas.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: frozenset question

2005-07-06 Thread Delaney, Timothy (Tim)
Steven D'Aprano wrote:

> If, over a thousand runs of the program, you save a millisecond of
> time in total, but it costs you two seconds to type the comment in
> the code explaining why you used frozenset instead of the more
> natural set, then your "optimization" is counter-productive. Even
> just considering the question is a waste of valuable developer time!
> THAT is the lesson of premature optimization: don't even THINK about
> optimizing code until you have it WORKING and you have MEASURED that
> it is too slow. 

Tell me about it. I've had to strongly argue against premature
optimisation in my current project. I said "make it work and we'll make
it fast at the end".

Well, I made my part work. Then I spent less than a week optimising and
made it over 1000 times faster, without obfuscating it. Meanwhile other
parts still don't work, but contain lots of premature optimisations that
combined have taken well over a week to put into place.

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


Re: Lisp development with macros faster than Python development?..

2005-07-06 Thread Rahul
Hi.
Instead of listing the difference ..here are some things that are
COMMON to both common lisp and python :

1.Dynamic typing.
2.garbage collection
3.powerful data structures
4.good object systems. (here people from lisp usually claim that clos
is the most powerful object system...but i think python and lisp are
comparable with none of them being better than the other. they are
different than each other. and i consider clos without mop to be
inferior. mop stands for meta object protocol...a thing which hasnt
been specified in the ansi lisp standard but is provided by most
implementations)
5.functions and types as first class objects
6.interactive development.

The differences:

1.Macros : Macros are extremely powerful and a double edges sword. Dont
believe anyone (whether they praise them or abhor them). Go and learn
them and decide for yourself.

2.Readability : Python is generally believed to be far more readable
than ANY other language. (Lisp isnt particularly unreadable).

The only way to really find out which is better is to learn both and
decide yourself.

i personally like python , lisp and c. now c evokes derision from both
python and lisp folks sometimes and thats incorrect too.
rahul

[EMAIL PROTECTED] wrote:
> I've been reading the beloved Paul Graham's "Hackers and Painters".
> He claims he developed a web app at light speed using Lisp and lots
> of macros.
>
> It got me curious if Lisp
> is inherently faster to develop complex apps in.  It would seem if you
> could create your own language in Lisp using macros that that would be
> quite an advantage
>
> I realize that Python has operator overloading and OOP so I'm not sure.
>
> Any ideas?  Any *evidence* one way or another?
> 
> thanks!
> 
> Chris

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread David Abrahams
Tom Anderson <[EMAIL PROTECTED]> writes:

> Comrades,
>
> During our current discussion of the fate of functional constructs in 
> python, someone brought up Guido's bull on the matter:
>
> http://www.artima.com/weblogs/viewpost.jsp?thread=98196
>
> He says he's going to dispose of map, filter, reduce and lambda. He's 
> going to give us product, any and all, though, which is nice of him.
>
> What really struck me, though, is the last line of the abstract:
>
> "I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme 
> folks. :-)"
>
> I disagree strongly with Guido's proposals, and i am not an ex-Lisp, 
> -Scheme or -any-other-functional-language programmer; my only other real 
> language is Java. I wonder if i'm an outlier.
>
> So, if you're a pythonista who loves map and lambda, and disagrees with 
> Guido, what's your background? Functional or not?

Not.  But I've gained a real appreciation for functional programming
from my use of both C++ and Python. 

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: I am a Java Programmer

2005-07-06 Thread Delaney, Timothy (Tim)
[EMAIL PROTECTED] wrote:

> I am a java programmer and I want to learn Python Please help me.

My condolences. I am a programmer who is currently forced to program in
Java.

These two sites will help you a lot in learning to program in Python:

http://www.catb.org/~esr/faqs/smart-questions.html
http://www.python.org/

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


RE: Conditionally implementing __iter__ in new style classes

2005-07-06 Thread Delaney, Timothy (Tim)
Thomas Heller wrote:

> I forgot to mention this: The Base class also implements a __getitem__
> method which should be used for iteration if the .Iterator method in
> the subclass is not available.  So it seems impossible to raise an
> exception in the __iter__ method if .Iterator is not found - __iter__
> MUST return an iterator if present.

Again, why not just let subclasses implement __iter__? Calling iter() on
an instance of the base class (or any subclass that does not implement
__iter__) will return an iterator that uses __getitem__. Calling iter()
on a subclass instance that does implement __iter__ will return the
iterator from the subclass __iter__.

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


Re: precision problems in base conversion of rational numbers

2005-07-06 Thread Raymond Hettinger
> > For a simple example, convert both 10247448370872321 and
> > 10247448370872319 from base ten to 4 digits of hex.  The calculations
> > need to be carried out to 15 places of hex (or 17 places of decimal)
> > just to determine whether the fourth hex digit is a 7 or 8:
> >
> > >>> hex(10247448370872321)
> > '0x246801L'
> > >>> hex(10247448370872319)
> > '0x2467ffL'
>
> I don't understand your simple example.
>
> log(10)/log(16) = 0.83048202372184058696757985737235
>
> Multiplying by the number of decimal digits (17) gives
>
> 14.11819440327128997844885757533
>
> Rounding up to an integer digit count, we need need 15 hex digits.
> Isn't that exactly what you concluded? Where does that 4 hex digit
> stuff come from?

It is part of the OP's problem spec.  Given a number x (which may be a
decimal, float, long integer, or rational), a base b, and a desired
precision p, compute the conversion to p-digits:

  >>> convert(x=10247448370872319L, b=16, p=4)
  '246800'

He wanted to know what decimal precision he needed to set to make the
conversion accurate to the last place.  The required precision for
intermediate calculations depends on how close x is to a representable
value in the target base.  The 16 digits are not known a priori since x
may be a rational, float, or decimal.  For instance, an internal
precision of 17 digits would also be needed for other nearby values of
x:

  >>> convert(x=Decimal("10247448370872319.1", b=16, p=4)
  '246800'

The number 17 does not just pop-out of a simple logarithm.  How many
internal digits of precision do you need for convert(math.pi, b=16,
p=5)?  If the result falls closely between reprentable values, the OP
may need to set his "magic number" to something larger than you would
have predicted.

If you want insight into why the OP's problem statement is deeper than
it appears, then ponder the mystery of why the following returns False:

  >>> x = 554459760520464551937111727196883414687442277344893869152167
  >>> float(x) == float(str(x))
  False

Hint, the two different underlying routines are trying to compute,
convert(x, b=2, p=53), without the benefit of arbitrary precision
arithmetic.


Raymond

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Steven Bethard
Daniel Schüle wrote:
> Removing lamdba would be reduce readability of Python, I think here
> for examble of code like
> 
> class App:
> 
> 
> def drawLines(self, event):
> from random import randint
> r = lambda : randint(1, 100)
> self.canvas.create_line(r(), r(), r(), r())
> 
> defining one extra function would only confuse and

But you just did define one extra function!!

If you're really afraid of two lines, write it as:

 def r(): randint(1, 100)

This is definitely a bad case for an anonymous function because it's not 
anonymous!  You give it a name, r.

> and what about creating one liner factories like
> from math import log10
> log = lambda basis: lambda x: log10(x) / log10(basis)
> log2 = log(2)
> log2(2**10) -> 10.0

This is slightly better, because at least one of your functions really 
is anonymous.  I'm not really sure I'm convinced that it's any better 
than this though:

 def log(base):
 def log_in_base(x):
 return log10(x)/log10(base)
 return log_in_base

because when I first read the code, I didn't catch the second, nested 
lambda.  Of course, with a syntax-highlighting editor, I probably would 
have.

Again though, to fix your abuse of anonymous function syntax for 
non-anonymous functions, you should write this as:

 def log(basis):
 return lambda x: log10(x) / log10(basis)

Or if you're afraid of multiple lines:

 def log(basis): return lambda x: log10(x) / log10(basis)

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


Re: Using Numeric 24.0b2 with Scientific.IO.NetCDF

2005-07-06 Thread bandw
I am having more problems with 24.0b2.  Consider the NetCDF file:

netcdf very_simple {
dimensions:
num = 2 ;
variables:
float T(num) ;
  T:mv = 5.0f ;
data:
 T = 1., 2. ;
}

and the python script:

import Numeric
from Scientific.IO.NetCDF import NetCDFFile
file = NetCDFFile("simple.nc","r")
T = file.variables["T"]

a = T.mv
print "T.mv = ", a
print "type(T.mv) = ", type(a)
print "len(T.mv) = ", len(a)
print "T.mv[0] = ", a[0]
print "len(T.mv[0]) = ", len(a[0])
print "type(T.mv[0]) = ", type(a[0])

which produces the output:

T.mv =  [ 5.]
type(T.mv) =  
len(T.mv) =  1
T.mv[0] =  5.0
len(T.mv[0]) =  1
type(T.mv[0]) =  

I can see no reason why T.mv[0] should be typed as an array.

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


Re: frozenset question

2005-07-06 Thread Steven D'Aprano
On Wed, 06 Jul 2005 10:15:31 -0700, George Sakkis wrote:

> Well, they *may* be interchangable under some conditions, and that was
> the OP's point you apparently missed. 

I didn't miss anything of the sort. That's why I spent 15 minutes actually
producing test cases to MEASURE if there was any detectable speed
differences between accessing set and frozenset instead of wasting time
worrying about "tiny" differences in performance that are almost certainly
lost in the noise in real code.

If, over a thousand runs of the program, you save a millisecond of time in
total, but it costs you two seconds to type the comment in the code
explaining why you used frozenset instead of the more natural set, then
your "optimization" is counter-productive. Even just considering the
question is a waste of valuable developer time! THAT is the lesson of
premature optimization: don't even THINK about optimizing code until you
have it WORKING and you have MEASURED that it is too slow.


-- 
Steven.


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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Daniel Schüle
I think in some contextes map is more readable than [f() for i in S]
because it's more verbatim
Removing lamdba would be reduce readability of Python, I think here
for examble of code like

class App:


def drawLines(self, event):
from random import randint
r = lambda : randint(1, 100)
self.canvas.create_line(r(), r(), r(), r())

defining one extra function would only confuse and
self.canvas.create_line(r(1, 100), r(1, 100), r(1, 100), r(1, 100))
is not very nice to look at

and what about creating one liner factories like
from math import log10
log = lambda basis: lambda x: log10(x) / log10(basis)
log2 = log(2)
log2(2**10) -> 10.0

I would consider it as a great loss for Python
if lambda will disappear

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


Re: Favorite non-python language trick?

2005-07-06 Thread Shai
I only saw this today... sorry about the late response. Anyway,
replying to your two messages at once:

Mike Meyer wrote:

> Last time I checked, dynamic binding variables were frowned on in LISP
> systems as well. Scheme doesn't have them.  Common LISP requires
> special forms to use them.

They're called "Special vars", and you need to define them (unlike
local LISP variables, which behave essentially like Python vars), but
then you use them just like other vars (that is, you usually bind them
with LET). This is the first I hear about them being ill-considered in
LISP; http://www.gigamonkeys.com/book/ is a recently published LISP
book which recommends them. I don't know about Scheme, but I think it
does have them.

The one "special" thing you see in every use of these vars in LISP is a
naming convention; as LISP symbols can contain most characters, they
are usually named with asterisks on both ends to distinguish them.
Thus, in the example above, the dynamic var would be named "*x*".

> The problem with the given use case is that it lets every routine in
> the call chain substitute it's own variable for the library parameter
> you want to use, with no local indication that this is going
> on. This makes bugs in dynamically scoped variables a PITA to find.

In LISP, the naming convention indeed takes care of that; and indeed, I
consider taking the LISP way would be better. The definition of x as
dynamic would then be not in bar nor its callers, but in the definition
of x, as in

dynamic x=10
def bar():
  print x

I specified the syntax as I did, specifically to make it match the
current definition of globals, which "enjoys" the same problems you
noted with my dynamics.

>
> >> x=10
> >> def foo():
> >>   # No need to define x as it is only read -- same as globals
> >>   print x
> >>
> >> def bar():
> >>   dynamic x
> >>   x = 11
> >>   foo()
> >>
> >> def baz():
> >>   bar() # prints 11
> >>   foo() # prints 10; the binding in bar is undone when bar exits
>
> Here's the problem with that. Consider this script:
>
> import foo
> x = 10
> def bar():
> print x
>
> foo.foogle(bar)
>
> If foo.foogle includes "dynamic x" and then invokes bar, bar could
> print anything. This makes the behavior of bar unpredictable by
> examining the sourc, with no hint that that is going on.
>
While I didn't write it explicitly, if both LISP and Python globals are
to be followed, the dynamic x should somehow be defined in the scope of
its module. On second thought, this means "dynamic" _must_ be added in
the variable definition, for foo.foogle will simply access it as
"othermodule.x", which doesn't differentiate globals from dynamics.

Either way, Python as it is now allows foo.foogle to change x even
without dynamic variables; it is accessible as barmodule.x. bar()
should expect to have other functions mess with its globals, and
dynamics are no different.

> > Given that it's a feature I don't want programmers using, I'd only be
> > willing to see it added to the language if you can show that it has no
> > overhead so long as you don't use it. I'm not sure that can be done.
>
That sounds like a fine requirement. Now, with my corrected
proposition, it would be implementable at the module-object level, so
that only module which use the feature, and modules which use them,
would be affected.

> Here's a proposal for dynamically bound variables that you should be
> able to implement without affecting the runtime behavior of code that
> doesn't use it.
>
> Instead of dynamic meaning "all references to the named variable(s)
> will be dynamic until this function exits", have it mean "the named
> variable(s) will be dynamic in this function." Whether it should only
> check local variables in the calling routines, check local + global,
> or check for all free variables, is an open question.
>
> I.e. - your example would be written:
>
> x = 10
> def foo():
> dynamic x
> print x
>
> def bar():
> x = 11
> foo()
>
> def baz():
> bar()   # prints 11
> foo()   # Possibly an error?
>

This introduces the same problem you noted with my original proposal,
but in reverse: Now, in bar(), you define and use a local variable, and
suddenly some library function changes its behavior misteriously.

> For my example above, bar would *always* print 10. Nothing that
> foo.foogle did would change that. However, you could write:
>
> import foo
> def bar():
> dynamic x
> print x
>
> foo.foogle(bar)
>
> In this case, bar will print whatever foo.foogle sets x to - and it's
> noted in the source to bar. This means that functions that don't
> declare a dynamic variable can be compiled to the same code they are
> compiled to now.
>

This is, I believe, disproved by my comment above.

Thanks for your time and effort,

Shai.

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


Re: Compatibility of recent GCC/Python versions

2005-07-06 Thread Robert Kern
David Abrahams wrote:
> Recently people testing Boost.Python with GCC on Linux have reported
> that the extensions being tested have to be compiled with exactly the
> same version of GCC as the Python they're being loaded into, or they
> get mysterious crashes.
> 
> That doesn't correspond to my past experience; it has always been true
> that, as long as the compiler used to build Python and the one used to
> build the extension have compatible 'C' ABIs, we've been okay.  Yes,
> if you were going to pass types like FILE* across the Python/C API,
> then you additionally need to be sure that the two compilers are using
> the same 'C' library.  That said, none of the Boost.Python tests do
> that.
> 
> I'm wondering if there has been a well-known recent change either in Python
> or GCC that would account for these new reports.  Any relevant
> information would be appreciated.

I've had intermittent problems on OS X and gcc-4.0 with, well, 
everything, Python-related or otherwise. So I ignore it and use gcc-3.3 
and g77-3.4 and live happily ever after.

-- 
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


Compatibility of recent GCC/Python versions

2005-07-06 Thread David Abrahams

Recently people testing Boost.Python with GCC on Linux have reported
that the extensions being tested have to be compiled with exactly the
same version of GCC as the Python they're being loaded into, or they
get mysterious crashes.

That doesn't correspond to my past experience; it has always been true
that, as long as the compiler used to build Python and the one used to
build the extension have compatible 'C' ABIs, we've been okay.  Yes,
if you were going to pass types like FILE* across the Python/C API,
then you additionally need to be sure that the two compilers are using
the same 'C' library.  That said, none of the Boost.Python tests do
that.

I'm wondering if there has been a well-known recent change either in Python
or GCC that would account for these new reports.  Any relevant
information would be appreciated.

Thanks,
-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-06 Thread Grant Edwards
On 2005-07-06, Ron Adam <[EMAIL PROTECTED]> wrote:

> It would be a way to set an argument as being optional without actually 
> assigning a value to it.  The conflict would be if there where a global 
> with the name baz as well.  Probably it would be better to use a valid 
> null value for what ever baz if for.  If it's a string then "", if its a 
> number then 0, if it's a list then [], etc...

Except those aren't "null values" for those types.  0 is a
perfectly good integer value, and I use it quite often. There's
a big difference between an "invalid integer value" and an
integer with value 0.

-- 
Grant Edwards   grante Yow!  I've read SEVEN
  at   MILLION books!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Benji York
Ron Adam wrote:
> "if extraargs:"  would evaluate to "if None:", which would evaluate to 
> "if:" which would give you an error.

In what way is "if None:" equivalent to "if:"?
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-06 Thread Ron Adam
Reinhold Birkenfeld wrote:

> Ron Adam wrote:
> 
>>Ron Adam wrote:
>>
>>
>>>And accessing an undefined name returned None instead of a NameError?
>>
>>I retract this.  ;-)
>>
>>It's not a good idea.  But assigning to None as a way to unbind a name 
>>may still be an option.
> 
> IMO, it isn't. This would completely preclude the usage of None as a value.
> None is mostly used as a "null value". The most prominent example is default
> function arguments:
> 
> def foo(bar, baz=None):
> 
> With None unbinding the name, what would you suggest should happen? baz being
> undefined in the function scope?

It would be a way to set an argument as being optional without actually 
assigning a value to it.  The conflict would be if there where a global 
with the name baz as well.  Probably it would be better to use a valid 
null value for what ever baz if for.  If it's a string then "", if its a 
number then 0, if it's a list then [], etc...

If it's an object... I suppose that would be None...  Oh well. ;-)

> Or, what should happen for
> 
> somedict[1] = None

Remove the key of course.

   var = somedict[1]  Would then give an error.

and

   (somedict[1] == None)  Would evaluate to True.


> ? Also, the concept of _assigning_ something to a name to actually _unassign_
> the name is completely wrong.

That's not anymore wrong than ([] == [None]) --> False.

Having a None value remove a name binding could make the above condition 
True.

> Of course, this is a possible way to unassign names if (and only if)
> (1) there is a real "undefined" value (not None)
> (2) unbound names return the undefined value
> 
> Look at Perl. Do we want to be like that? ;)
> 
> Reinhold

The problem I had with perl is that number of symbols and ways of 
combining them can be quite confusing when you don't use it often.  So 
it's either a language you use all the time... or avoid.

Anyway, there seems to be enough subtle side effects both small and 
large to discount the idea.  While implementing it may be possible, it 
would require a number of other changes as well as a different way of 
thinking about it, so I expect it would be disliked quite a bit.

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


Re: Lisp development with macros faster than Python development?..

2005-07-06 Thread Scott David Daniels
François Pinard wrote:
> My feeling at the time was that Scheme is a very fast language to write
> into, and in which one can implement new concepts cleanly and compactly.
> Maybe Python is a bit slower to write, but this is compensated by the
> fact Python is more legible when it comes to later maintenance, or when
> many people have to share work on a big set of sources.
> 
> There is some heaviness and complexity in Python internals, Scheme are
> purer and simpler by comparison.  On its bright side, Python has a nice
> and comprehensive library, and an interesting community of users.  These
> probably make most of the difference.

Well said. Writing speed is not everything; if it is, APL and Scheme
win (and the evil Perl for string processing).

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


Re: Scipy - Latex Annotations in plots

2005-07-06 Thread Robert Kern
Matthias R. wrote:
> Unfortunately matplotlib is only a 2D-plotting library.
> 
> Do you know another one with 3D-capabilities as well?

There's PyX.

> That would be very nice, 

Yes, yes it would.

-- 
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: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Bruno Desthuilliers
Stian Søiland a écrit :
> 
(snip)
> Hey, I know!
> 
> t = python.util.ImmutableArrayList.fromCollection(L.getAbstractCollection())
> 
> python.util.functional.applyFunctionOnCollection(
> (class implements python.util.functional.AnonymousFunction:
> def anonymousFunction(x):
> return x+1
> ), L)
> 
Reminds me of something, but what ?-)


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


Re: Scipy - Latex Annotations in plots

2005-07-06 Thread Bill Mill
> Robert Kern wrote:
> 
> > fortuneteller wrote:
> >> Hello,
> >>
> >> I'm quite new to python and Scipy.
> >> Anyway I want to use it to plot graphs.
> >> Does anybody know if there is the possibility to use Latex in SciPy's
> >> plotting functions like gplt?
> >
> > I don't believe so. matplotlib, however, does have this functionality in
> > recent releases.

On 7/6/05, Matthias R. <[EMAIL PROTECTED]> wrote:
> Unfortunately matplotlib is only a 2D-plotting library.
> 
> Do you know another one with 3D-capabilities as well?
> That would be very nice,
> 

Perhaps gnuplot.py (http://gnuplot-py.sourceforge.net/) will work for
you? It is a thin wrapper around Gnuplot, which is very good at
producing ps format images, and is capable of producing 3 dimensional
graphs.

Peace
Bill Mill
bill.mill at gmail.com

PS please try to not top-post, you can lose the rest of the thread easily
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Bruno Desthuilliers
Tom Anderson a écrit :
> Comrades,
> 
> During our current discussion of the fate of functional constructs in 
> python, someone brought up Guido's bull on the matter:
> 
> http://www.artima.com/weblogs/viewpost.jsp?thread=98196
> 
> He says he's going to dispose of map, filter, reduce and lambda. He's 
> going to give us product, any and all, though, which is nice of him.
> 
> What really struck me, though, is the last line of the abstract:
> 
> "I expect tons of disagreement in the feedback, all from 
> ex-Lisp-or-Scheme folks. :-)"
> 
> I disagree strongly with Guido's proposals, and i am not an ex-Lisp, 
> -Scheme or -any-other-functional-language programmer; my only other real 
> language is Java. I wonder if i'm an outlier.
> 
> So, if you're a pythonista who loves map and lambda, and disagrees with 
> Guido, what's your background? Functional or not?
> 

I discovered FP with David Mertz's papers about FP in Python. I had 
never read nor write a line of lisp, scheme, haskell, caml etc before. 
And I'd certainly start thinking of choosing another MYFL if anonymous 
functions where to disappear from Python. Note that I said "anonymous 
functions", not "lambda". Concerning map, filter, reduce etc, these 
functions can live in a separate module, and this wouldn't bother me. 
But anonymous functions are part of the language syntax, so there is no 
work-around.

My 2 (euro) cents
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am a Java Programmer

2005-07-06 Thread Luis M. Gonzalez
I'm sorry for you, nobody deserves to program in Java ...
I'm glad you decided to stand up for your human rights. Go learn
python!

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


Re: Strange os.path.exists() behaviour

2005-07-06 Thread Michael Hoffman
Jeff Epler wrote:

> Here's the bug.  You're using Windows.

QOTW (speaking as someone who is using Windows right now).
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


PyNSol: Objects as Scaffolding

2005-07-06 Thread Michael Tobis
An article of mine, entitled "PyNSol: Objects as Scaffolding"  has
appeared in Computing in Science and
Engineering. You can read it at

http://www.computer.org/portal/site/cise/

or alternatively at

http://geosci.uchicago.edu/~tobis/ciseps.pdf

It's not so much an article about a software project as it is an
article using that project to present an alternative way of thinking
about how object oriented programming (and Python!) can relate to high
performance simulations.

I welcome comments.

mt
--
Michael Tobis
Geophysical Sciences
University of Chicago

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


out of office auto-reply

2005-07-06 Thread Frank Fuchs
Dear sender,

I am on vacation up to and including Sunday, July 10th, 2005 and I will be
travelling on Monday and Tuesday after.
My first day back in the office might be Wednesday, July 13th, 2005 - at which
time I will have access to email again.
If it's urgent you can try my mobile on Monday/Tuesday, July 11th/12th, but you
will not be able to reach me during my vacation.

During my absence, please contact one of my colleagues in management or your
sales representative.


Sincerely,

Frank Fuchs
Managing Director, CIO and CTO
SOFTPRO Group

SOFTPRO Software Professional GmbH & Co. KG
Wilhelmstr. 34
D-71034 Boeblingen
Germany
www.signplus.com
www.softpro.de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scipy - Latex Annotations in plots

2005-07-06 Thread Matthias R.
Unfortunately matplotlib is only a 2D-plotting library.

Do you know another one with 3D-capabilities as well?
That would be very nice, 

thank you, 

Matthias

Robert Kern wrote:

> fortuneteller wrote:
>> Hello,
>> 
>> I'm quite new to python and Scipy.
>> Anyway I want to use it to plot graphs.
>> Does anybody know if there is the possibility to use Latex in SciPy's
>> plotting functions like gplt?
> 
> I don't believe so. matplotlib, however, does have this functionality in
> recent releases.
> 

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Dan Sommers
On Wed, 6 Jul 2005 20:42:51 +0200,
Stian Søiland <[EMAIL PROTECTED]> wrote:

> I'm all for it. I would even be tempted of changing def to function,
> but it would look stupid in:

> class A:
> function make_my_day(self):
> return "Your day"
> a = A()


> since a.make_my_day() is really a method, not a standalone function. 
> We could use "function" instead of "lambda" though =)

So use "method" instead, which has the added advantage of implicity
declaring an extra argument named "this":

class A:
method __init__():
this.x = 0
method make_my_day(foo):
this.x += foo

there-aren't-enough-winks-in-the-universe'ly yours,
Dan

-- 
Dan Sommers

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

Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Ron Adam
Stian Søiland wrote:

> On 2005-07-06 16:33:47, Ron Adam wrote:
> 
> 
>>*No more NamesError exceptions!
>> print value
>> >> None
> 
> 
> So you could do lot's of funny things like:
> 
> def my_fun(extra_args=None):
> if not extraargs:
> print "Behave normally"
> extra_args = 1337
> 
> if extraargs:
> asdkjaskdj
> ..
> if extra_args:
> kajsdkasjd

Yes, returning None from an undefined name is DOA.

In the above case you would get an error by the way.

"if extraargs:"  would evaluate to "if None:", which would evaluate to 
"if:" which would give you an error.


>>*No initialization needed for a while loop!
>>
>> while not something:
>> if :
>> something = True
> 
> 
> This is the only "good" case I could find, but opening for a lots of
> errors when you get used to that kind of coding:

It would need to be.. while not (something==None):  and the compiler 
would need to handle it as a special case.  But this one could still 
work without allowing something=undefined to be valid.

> while not finished:
> foo()
> finished = calculate_something()
> 
> (..)
> (..)  # Added another loop
> while not finished:
> bar()
> finished = other_calculation()
> 
> Guess the amount of fun trying to find out the different errors that
> could occur when bar() does not run as it should because the previous
> "finished" variable changes the logic.

It's not really differnt than any other value test we currently use.

 notfinished = True
 while notfinished:
 notfinished = (condition)

 # Need to set notfinished back to True here.
 while notfinished:
 


>>*Test if name exists without using a try-except!
>> if something == None:
>> something = value
> 
> Now this is a question from newcomers on #python each day.. "How do I
> check if a variable is set?".
> 
> Why do you want to check if a variable is set at all? If you have so
> many places the variable could or could not be set, your program design
> is basically flawed and must be refactored.

There's a few places the Python library that do exactly that.

try:
value
except:
value = something

I admit it's something that should be avoided if possible because if 
there's doubt that a name exists, then there would also be doubt 
concerning where it came from and weather or not it's value/object is valid.

Anyway, it was an interesting but flawed idea, I should of thought more 
about it before posting it.

Cheers,
Ron







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


Re: Use cases for del

2005-07-06 Thread Reinhold Birkenfeld
Ron Adam wrote:
> Ron Adam wrote:
> 
>> And accessing an undefined name returned None instead of a NameError?
> 
> I retract this.  ;-)
> 
> It's not a good idea.  But assigning to None as a way to unbind a name 
> may still be an option.

IMO, it isn't. This would completely preclude the usage of None as a value.
None is mostly used as a "null value". The most prominent example is default
function arguments:

def foo(bar, baz=None):

With None unbinding the name, what would you suggest should happen? baz being
undefined in the function scope?

Or, what should happen for

somedict[1] = None

The same as

del somedict[1]

? Also, the concept of _assigning_ something to a name to actually _unassign_
the name is completely wrong.

Of course, this is a possible way to unassign names if (and only if)
(1) there is a real "undefined" value (not None)
(2) unbound names return the undefined value

Look at Perl. Do we want to be like that? ;)

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


Re: Folding in vim

2005-07-06 Thread Bill Mill
On 7/6/05, Terry Hancock <[EMAIL PROTECTED]> wrote:
> On Tuesday 05 July 2005 03:53 pm, Renato Ramonda wrote:
> > Why not use just spaces? Vim simplifies this immensely:
> >
> > set tabstop=4
> > set shiftwidth=4
> > set expandtab
> > set smarttab
> > set autoindent
> >
> > AFAICT this gives me all spaces, 4 spaces indent, tab inserts spaces and
> > backspace over a block of 4 spaces deletes all of them (just like
> > deleting a tab).
> 
> Yep, this is what I just set up in my .vimrc.  Works beautifully.
> 

I don't use any of the fancy indenters; instead, I just add

set foldmethod=indent

to my .vimrc (_vimrc on windows), along with most of the
aforementioned options (I don't like smarttab); it works nearly
perfectly. Then zo opens the fold under the cursor one level, zO opens
it recursively, zc and zC close it non- and recursively. zr opens all
folds one level, zR opens them all recursively, zm closes them all one
level, and zM closes them all recursively.

It's pretty sweet. Maybe we should have a big Vim-python tip-a-thon thread?

Peace
Bill Mill
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange os.path.exists() behaviour

2005-07-06 Thread Jeff Epler
Pierre wrote:
> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
   ^^^
Here's the bug.  You're using Windows.  It's a filesystem, but not as we know 
it...

Anyway, You are getting exactly what the low-level Windows APIs return.

Here's a small "C" program.  It prints "0" next to the filename if the
file exists, -1 otherwise, as described at

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt__access.2c_._waccess.asp

int main(int argc, char **argv) {
int i;
for(i=1; idir
 Volume in drive C has no label.
 Volume Serial Number is 171D-4D2A

 Directory of C:\TMP\example

07/06/05  03:04p  .
07/06/05  03:04p  ..
07/06/05  03:05p 3 exist
   3 File(s)  3 bytes

C:\TMP\example>x:a.exe exist exist. exist nonexist nonexist. nonexist...
   exist: 0
  exist.: 0
   exist: 0
nonexist: -1
   nonexist.: -1
 nonexist...: -1

C:\TMP\example>type nonexist
The system cannot find the file specified.

C:\TMP\example>type exist


C:\TMP\example>

As you can see, not only does Windows think that "exist" exists, but it can
successfully "type" its contents too!

Jeff


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

Strange os.path.exists() behaviour

2005-07-06 Thread Pierre Quentel
os.path.exists(path) returns True if "path" exists

But on Windows it also returns True for "path" followed by any number of 
dots :

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 os
 >>> os.path.exists('Lib/os.py')
True# expected
 >>> os.path.exists('Lib/os.py.')
True# unexpected
 >>> os.path.exists('Lib/os.py.')
True# unexpected
 >>>

Is there a reason for this ? Is there a test that returns True only for 
the really existing path ?

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


Re: inheriting file object

2005-07-06 Thread Jeremy
harold fellermann wrote:
>>I don't know if I should be inheriting file or just using a file 
>>object.
>>  How would I determine which one would be more appropriate?
> 
> 
> Inheritance is often refered to as an IS relation, whereas using an 
> attribute
> is a HAS relation.
> 
> If you inherit from file, all operations for files should be valif for 
> your
> class also. Usually the file-operations would be directly inherited and 
> not
> overwritten.
> 
> However, if you don't want to expose all file functionalities, a HAS 
> relation
> is more appropriate. if you plan to use your class as a file handle, 
> e.g. for
> formatting output in a special way, I woould prefer to make the file an 
> attribute:

> If you would tell as your use case, it would be easier to give you an 
> advice.

That is an excellent explanation and the example is similar to what I 
want to do.  I have a file I want to look through and change if needed. 
I think I will follow you suggestion and not inherit from the file object.
Thanks,
Jeremy

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


Re: flatten(), [was Re: map/filter/reduce/lambda opinions ...]

2005-07-06 Thread Stian Søiland
On 2005-07-06 00:50:30, Ron Adam wrote:

> This is probably the more correct way to do it. :-)
> 
> def flatten(seq):
>  i = 0
>  while i!=len(seq):
>  while isinstance(seq[i],list):
>  seq[i:i+1]=seq[i]
>  i+=1
>  return seq

Or what about a recursive generator?

a = [1,2,[[3,4],5,6],7,8,[9],[],]

def flatten(item):
try:
iterable = iter(item)
except TypeError:
yield item  # inner/final clause
else:
for elem in iterable:
# yield_return flatten(elem)
for x in flatten(elem):
yield x

print list(flatten(a))


Of course, one of the problems here is that there is no way to
yield_return except to create yet another stupid-looking for-loop. This
is one of the flaws in the current generator functionallity of Python.

Using yield_return could also make it more obvious that the result is in
fact a generator in functions that wrap generators.

-- 
Stian Søiland   Work toward win-win situation. Win-lose
Trondheim, Norway   is where you win and the other lose.
http://soiland.no/  Lose-lose and lose-win are left as an
exercise to the reader.  [Limoncelli/Hogan]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: from date/time string to seconds since epoch

2005-07-06 Thread Peter Kleiweg
[EMAIL PROTECTED] schreef op de 6e dag van de hooimaand van het jaar 2005:

> You can calculate the offset of where you are like this:
>
> [EMAIL PROTECTED]:~ $ python
> Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
> [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> py> import time
> py> offset = 0
> py> if time.daylight:
> py. offset = time.altzone
> py. else:
> py. offset = time.timezone
> py.
> py> print offset
> -7200
> py>
>
> You can use time.time() to get the UTC time, then add the offset.

The offset is for this moment, not for the date and time of the
string parsed.

-- 
Peter Kleiweg  L:NL,af,da,de,en,ia,nds,no,sv,(fr,it)  S:NL,de,en,(da,ia)
info: http://www.let.rug.nl/~kleiweg/ls.html

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


Re: map/filter/reduce/lambda opinions and backgroundunscientificmini-survey

2005-07-06 Thread Terry Reedy

"George Sakkis" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>
>> "George Sakkis" <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>> > Still it's hard to explain why four specific python keywords - def,
>> > del, exec and elif - were chosen to be abbreviated,
>>
>> Precedence in other languages and CS usage?
>
> What precedence ? I don't know of another language that uses def or del

DOS used DEL, BASIC used DEF.

tjr 



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


Re: Use cases for del

2005-07-06 Thread Ron Adam
Ron Adam wrote:

> And accessing an undefined name returned None instead of a NameError?

I retract this.  ;-)

It's not a good idea.  But assigning to None as a way to unbind a name 
may still be an option.

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


RE: How do you program in Python?

2005-07-06 Thread Sells, Fred
I'm old school and have been very happy with emacs (on windows) and the
python extensions.  I just edit my file and hit control-C twice and it runs.
I'm also using eclipse with PyDev and it's ok, but sluggish.

-Original Message-
From: anthonyberet [mailto:[EMAIL PROTECTED]
Sent: Sunday, July 03, 2005 12:35 PM
To: python-list@python.org
Subject: How do you program in Python?


My question isn't as all-encompassing as the subject would suggest...

I am almost a Python newbie, but I have discovered that I don't get 
along with IDLE, as i can't work out how to run and rerun a routine 
without undue messing about.

What I would really like is something like an old-style BASIC 
interpreter, in which I could list, modify and test-run sections of 
code, to see the effects of tweaks, without having to save it each time, 
or re-typing it over and over (I haven't even worked out how to cut and 
paste effectively in the IDLE environment).

I see lots of alternate IDEs etc, but which would allow me the simple 
interface that I have described? - I really don't know about IDEs in 
general, and I suspect I would be out of my depth with one of those.

Thanks, and feel free to mock ;)
-- 
http://mail.python.org/mailman/listinfo/python-list

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threads and sleep?

2005-07-06 Thread Jonathan Ellis
Peter Hansen wrote:
> Jonathan Ellis wrote:
> > Peter Hansen wrote:
> >>Or investigate the use of Irmen's Pyro package and how it could let you
> >>almost transparently move your code to a *multi-process* architecture
> >
> > Unless you're doing anything that would require distributed locking.
> > Many if not most such projects do, which is why almost everyone prefers
> > to use threads on an SMP machine instead of splitting it across
> > multiple smaller boxes.
>
> I can't address the issue of whether or not "most" such projects require
> distributed locking, because I'm not familiar with more than half of
> such projects, as you appear to be. 

Your sarcasm is cute, I suppose, but think about it for a minute.  If
the opposite of what I assert is true, why would even the mainstream
press be running articles along the lines of "multicore CPUs mean
programming will get tougher because locking is hard to get right and
you can't just scale by relying on the cpu to run your one
thread/process really fast anymore."

http://www.gotw.ca/publications/concurrency-ddj.htm for one example.

-Jonathan

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


Re: Avoiding NameError by defaulting to None

2005-07-06 Thread Ron Adam
Scott David Daniels wrote:

> Ron Adam wrote:
> 
>> Dan Sommers wrote:
>>
>>> Lots more hard-to-find errors from code like this:
>>> filehandle = open( 'somefile' )
>>> do_something_with_an_open_file( file_handle )
>>> filehandle.close( )
>>
>>
>> If do_something_with_an_open_file() is not defined. Then you will get:
>> TypeError: 'NoneType' object is not callable
>>
>>
>> If "file_handle" (vs "filehandle") is None.  Then you will still get 
>> an error as soon as you tried to use the invalid file handle.
> 
> Ah, but where you use it can now far from the error in the source.  The
> None could get packed up in a tuple, stored in a dictionary, all manner
> of strange things before discovering it was an unavailable value.  I
> would love the time back that I spent chasing bugs when Smalltalk told
> me (I forget the exact phrasing) "nil does not respond to message abc."
> My first reaction was always, "of course it doesn't, this message is
> useless."  You really want the error to happen as close to the problem
> as possible.
> 
> --Scott David Daniels
> [EMAIL PROTECTED]


Yep, I concede.  The problem is if undefined names return None, and None 
deletes a name,  then assigning a undefined name to an existing name, 
will delete it silently.

Definitely Not good!

So it should give an error as it currently does if an undefined name is 
used on the right side of an =.

It could still work otherwise to unbind names, and (undefined_name == 
None) could still be a valid way to check if a name is defined without 
using a try-except.

But it would definitely be a Python 3000 change as all the functions 
that return None would then cause errors.

Cheers,
Ron

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


RE: I am a Java Programmer

2005-07-06 Thread Sells, Fred
It takes great courage to turn from the dark side; let the pforce be with
you.

Also, go to Borders, get the python books and a Latte and figure out if one
of
the many books is written in a style that you like.

-Original Message-
From: bruno modulix [mailto:[EMAIL PROTECTED]
Sent: Monday, July 04, 2005 5:52 AM
To: python-list@python.org
Subject: Re: I am a Java Programmer


[EMAIL PROTECTED] wrote:
> I am a java programmer 
Too bad :(

> and I want to learn Python 
So there's still hope !-)

> Please help me.
1/ download and install Python
2/ go thru the 'dive into Python' and 'Thinking in Python' free books
3/ post here when you're in doubt or in trouble...

And don't forget: Python is *not* Java !-)

-- 
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

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: from date/time string to seconds since epoch

2005-07-06 Thread [EMAIL PROTECTED]
You can calculate the offset of where you are like this:

[EMAIL PROTECTED]:~ $ python
Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
py> import time
py> offset = 0
py> if time.daylight:
py. offset = time.altzone
py. else:
py. offset = time.timezone
py.
py> print offset
-7200
py>

You can use time.time() to get the UTC time, then add the offset.

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Ron Adam
Dan Sommers wrote:

>> AttributeError: 'NoneType' object has no attribute 'read'
> 
> 
> This is the one of which I was thinking.  So you see this error at the
> end of a (long) traceback, and try to figure out where along the (long)
> line of function calls I typed the wrong name.  Currently, the very end
> of the traceback points you right at the bad code and says "NameError:
> name 'filehandle' is not defined," which tells me (very nearly) exactly
> what I did wrong.

The actual error could be improved a bit to refer the the name of the 
and line the error is in.  Which would help some.

AttributeError: 'NoneType' object "file_handle" has no attribute 
'read'


> I guess it depends on how long your traceback is and how big those
> functions are.  Also, from the Zen:
> 
> Explicit is better than implicit.
> 
> although from previous threads, we know that every pythonista has his or
> her own definitions of "explicit" and "implicit."

True, but this isn't any different than any other 'Type' error, or value 
error.  And considerably easier to find than one off errors.

There would be more restrictions on None than there are now so it 
wouldn't be as bad as it seems.  For example passing a None in a 
function would give an error as the name would be deleted before the 
function actually gets it.

So doing this would give an error for functions that require an argument.

 def foo(x):
 return x

 a = None
 b = foo(a)#  error because a dissapears before foo gets it.

 >>TypeError: foo() takes exactly 1 argument(0 given)


So they wouldn't propagate like you would expect.

Hmmm interesting that would mean... lets see.


1. var = None# removes ref var,  this is ok

2. None = var# give an error of course

3. var = undefined_var   # same as "var = None",  that's a problem!

Ok... this must give an error because it would delete var silently! 
Definitely not good.  So going on, on that basis.

4. undefined == None # Special case, evaluates to True.

5.  def foo():return None   # same as return without args

6.  x = foo()#  Would give an error if foo returns None

This might be an improvement over current behavior.  Breaks a lot of 
current code though.

7.  if undefined:# error

8.  if undefined==None   #  Special case -> True

Good for checking if vars exist.

9.  if undefined==False  #  Error, None!=False (or True)

9.  while undefined: # error

10  while undefined==None:

Possible loop till defined behavior.


Ok... and undefined var returning None is a bad idea, but using None to 
del names could still work.  And (undefined==None) could be a special 
case for checking if a variable is defined.  Otherwise using an 
undefined name should give an error as it currently does.

Cheers,
Ron


> Regards,
> Dan

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


Re: Use cases for del

2005-07-06 Thread Benji York
Stian Søiland wrote:
> Yes, and we can make 
> 
> someunknownlist[] = 2
> 
> magically do someunknownlist = list() and append 2.

I hope you're being sarcastic.  :)

If not, why don't you like:

some_list = [2]
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientificmini-survey

2005-07-06 Thread Stian Søiland
On 2005-07-06 07:00:04, Steven D'Aprano wrote:

> map(lambda x: if x == 0: 1; else: math.sin(x)/x,
>  myList)

And now for the "readable" list comprehension version:

[x==0 and 1 or math.sin(x)/x for x in myList]

Now even though I'm into the short-circuiting of and-or and even
occasionally have used such masturbation techniques as this, I don't
think it qualifies as pythonic.

If it was me, I would probably even have written:

[x and math.sin(x)/x or 1 for x in myList]

-- 
Stian Søiland   Work toward win-win situation. Win-lose
Trondheim, Norway   is where you win and the other lose.
http://soiland.no/  Lose-lose and lose-win are left as an
exercise to the reader.  [Limoncelli/Hogan]
-- 
http://mail.python.org/mailman/listinfo/python-list


from date/time string to seconds since epoch

2005-07-06 Thread Peter Kleiweg

Is there a safe and clean way to parse a date/time string into
seconds since epoch?

I have a string with date and time in GMT. I can get the correct
value using this:


#!/usr/bin/env python
import os
os.environ['TZ'] = 'UTC'
import time
s = 'Wed, 06 Jul 2005 16:49:38 GMT'
seconds = time.mktime(time.strptime(s, '%a, %d %b %Y %H:%M:%S %Z'))


However, I also need conversions to localtime. Setting TZ to UTC
before importing the time module won't let me do this. Changing
TZ after importing time has no effect.


-- 
Peter Kleiweg  L:NL,af,da,de,en,ia,nds,no,sv,(fr,it)  S:NL,de,en,(da,ia)
info: http://www.let.rug.nl/~kleiweg/ls.html

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Stian Søiland
On 2005-07-06 16:33:47, Ron Adam wrote:

> *No more NamesError exceptions!
>  print value
>  >> None

So you could do lot's of funny things like:

def my_fun(extra_args=None):
if not extraargs:
print "Behave normally"
extra_args = 1337

if extraargs:
asdkjaskdj
..
if extra_args:
kajsdkasjd

and get no errors at all, but switching back and forth between the
different behavours because you actually did expect None, but from an
EXISTING variable.

> *No initialization needed for a while loop!
> 
>  while not something:
>  if :
>  something = True

This is the only "good" case I could find, but opening for a lots of
errors when you get used to that kind of coding:

while not finished:
foo()
finished = calculate_something()

(..)
(..)  # Added another loop
while not finished:
bar()
finished = other_calculation()

Guess the amount of fun trying to find out the different errors that
could occur when bar() does not run as it should because the previous
"finished" variable changes the logic.

If you want to experiment with such designs, all you need to do is to
start your code with  *Test if name exists without using a try-except!
>  if something == None:
>  something = value

Now this is a question from newcomers on #python each day.. "How do I
check if a variable is set?".

Why do you want to check if a variable is set at all? If you have so
many places the variable could or could not be set, your program design
is basically flawed and must be refactored.

-- 
Stian Søiland   Work toward win-win situation. Win-lose
Trondheim, Norway   is where you win and the other lose.
http://soiland.no/  Lose-lose and lose-win are left as an
exercise to the reader.  [Limoncelli/Hogan]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The GIL, callbacks, and GPFs

2005-07-06 Thread Thomas Heller
Francois De Serres <[EMAIL PROTECTED]> writes:

> Hello,
>
> I'm chasing a GPF in the interpreter when running my extension module.
> It's not very elaborated, but uses a system (threaded) callback, and
> therefore the GIL.
> Help would be mucho appreciated. Here's the rough picture:
>

> static void external_callback(const Bag * const bag) {   if
> (my_callback && (my_callback != Py_None)) {
> PyObject * arglist = NULL;
> PyObject * result = NULL;
> arglist = Py_BuildValue("(s#)", bag->data, bag->size);
>   /* do it */
> PyGILState_STATE gil = PyGILState_Ensure();

You're calling Py_BuildValue without holding the GIL.  Not sure if
that's the reason for your problems, but I don't think its ok.

> result = PyEval_CallObject(my_callback, arglist);
> PyGILState_Release(gil);
>   Py_DECREF(arglist);
> Py_DECREF(result);  }
> }

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


Re: inheriting file object

2005-07-06 Thread harold fellermann
> I don't know if I should be inheriting file or just using a file 
> object.
>   How would I determine which one would be more appropriate?

Inheritance is often refered to as an IS relation, whereas using an 
attribute
is a HAS relation.

If you inherit from file, all operations for files should be valif for 
your
class also. Usually the file-operations would be directly inherited and 
not
overwritten.

However, if you don't want to expose all file functionalities, a HAS 
relation
is more appropriate. if you plan to use your class as a file handle, 
e.g. for
formatting output in a special way, I woould prefer to make the file an 
attribute:

class myFile :
def __init__(self,fname,mode="r") :
self.file = file(fname,mode)

def write_formatted(self,string) :
# format string
self.file.write()


If you would tell as your use case, it would be easier to give you an 
advice.

- harold -

--
Yesterday is but today's memory and Tomorrow is today's dream.
--

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


Re: Use cases for del

2005-07-06 Thread Stian Søiland
On 2005-07-06 18:10:16, Ron Adam wrote:

> But what if assigning a name to None actually unbound it's name?
> And accessing an undefined name returned None instead of a NameError?

Yes, and we can make 

someunknownlist[] = 2

magically do someunknownlist = list() and append 2.


Please.

-- 
Stian Søiland   Work toward win-win situation. Win-lose
Trondheim, Norway   is where you win and the other lose.
http://soiland.no/  Lose-lose and lose-win are left as an
exercise to the reader.  [Limoncelli/Hogan]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Stian Søiland
On 2005-07-06 01:46:05, Steven D'Aprano wrote:

> I had NEVER even heard the word "tuple" before learning Python. I spent
> weeks mispelling it as "turple", and I finally had to look it up in a
> dictionary to see if it was a real English word. Out of the four English
> dictionaries in my house, none of them have the word.

Agree, I have the problem of writing "tupple" in all comments and
documentations. It's a weird word indeed =)

> t = immutable_list(L)
> map(anonymous_function x: x+1, L)

Hey, I know!

t = python.util.ImmutableArrayList.fromCollection(L.getAbstractCollection())

python.util.functional.applyFunctionOnCollection(
(class implements python.util.functional.AnonymousFunction:
def anonymousFunction(x):
return x+1
), L)



-- 
Stian Søiland   Work toward win-win situation. Win-lose
Trondheim, Norway   is where you win and the other lose.
http://soiland.no/  Lose-lose and lose-win are left as an
exercise to the reader.  [Limoncelli/Hogan]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Stian Søiland
On 2005-07-06 02:46:27, George Sakkis wrote:

> So, who would object the full-word versions for python 3K ?
> def -> define
> del -> delete
> exec -> execute
> elif -> else if

I'm all for it. I would even be tempted of changing def to function, but
it would look stupid in:

class A:
function make_my_day(self):
return "Your day"
a = A()


since a.make_my_day() is really a method, not a standalone function. 
We could use "function" instead of "lambda" though =)

Objections for the "else if" might be that it sounds like you can
replace "else if" with "else x=94" if you want. Thumbs up for "else if"
because it explains what it is much better than "elif".  "elseif" ? 

-- 
Stian Søiland   Work toward win-win situation. Win-lose
Trondheim, Norway   is where you win and the other lose.
http://soiland.no/  Lose-lose and lose-win are left as an
exercise to the reader.  [Limoncelli/Hogan]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good starterbook for learning Python?

2005-07-06 Thread Luis M. Gonzalez
Before buying a book, I suggest starting out with at least one of these
beginners tutorials available in internet:

- Non-Programmers Tutorial For Python by  Josh Cogliati
(honors.montana.edu/~jjc/easytut/easytut/)
- A Byte of Python by Swaroop CH (www.byteofpython.info)

There are many others, but these ones are very good. The first one is
best for someone who knows nothing about programing, and the second one
is probably better for you, since you already have some experience.
It's good for absolute beginners though.

Books:
- Learning Python by Mark Lutz
- Core Python by Wesley Chun

Regards,
Luis

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


Re: inheriting file object

2005-07-06 Thread Jeremy
Jeremy Jones wrote:

> Something like this?  I put the following code in test_file.py:
> 
> class MyFile(file):
> def doing_something(self):
> print "in my own method"
> 
> 
> And used it like this:
> 
> In [1]: import test_file
> 
> In [2]: f = test_file.MyFile("foobar.file", "w")
> 
> In [3]: f.write("foo\n")
> 
> In [4]: f.doing_something()
> in my own method
> 
> 
> But do you really need to subclass file, or can you just use a file 
> instance in your class?
> 
> 
> Jeremy Jones  
I don't know if I should be inheriting file or just using a file object. 
  How would I determine which one would be more appropriate?
Thanks,
Jeremy

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


Re: Good starterbook for learning Python?

2005-07-06 Thread Renato Ramonda
Lennart ha scritto:

> Programming Python will I sell as a book that i read secondly, and use as a
> reference. 

I'd like to suggest also "Thinking like a CS in python": a schoolbook 
used in real classes to teach the basis of programming.

-- 
Renato

Usi Fedora? Fai un salto da noi:
http://www.fedoraitalia.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Folding in vim

2005-07-06 Thread Renato Ramonda
Terry Hancock ha scritto:

> 
> Yep, this is what I just set up in my .vimrc.  Works beautifully.

And (you probably already know, but it could be of use to others) you 
can bind the activation of some or all of those commands to au 
(autocommand) depending on the file extension.

That way you can have 8 spaces real tabs in C files, for examples, 
without touching your conf.

-- 
Renato

Usi Fedora? Fai un salto da noi:
http://www.fedoraitalia.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scipy - Latex Annotations in plots

2005-07-06 Thread Robert Kern
fortuneteller wrote:
> Hello, 
> 
> I'm quite new to python and Scipy.
> Anyway I want to use it to plot graphs.
> Does anybody know if there is the possibility to use Latex in SciPy's
> plotting functions like gplt?

I don't believe so. matplotlib, however, does have this functionality in 
recent releases.

-- 
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: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Dan Sommers
On Wed, 06 Jul 2005 15:18:31 GMT,
Ron Adam <[EMAIL PROTECTED]> wrote:

> Dan Sommers wrote:
>> On Wed, 06 Jul 2005 14:33:47 GMT,
>> Ron Adam <[EMAIL PROTECTED]> wrote:
>> 
>>> Since this is a Python 3k item...  What would be the consequence of
>>> making None the default value of an undefined name?  And then assigning
>>> a name to None as a way to delete it?
>> [ ... ]
>> 
>>> Any drawbacks?
>> Lots more hard-to-find errors from code like this:
>> filehandle = open( 'somefile' )
>> do_something_with_an_open_file( file_handle )
>> filehandle.close( )
>> Regards,
>> Dan

[ ... ]

> If "file_handle" (vs "filehandle") is None.  Then you will still get an
> error as soon as you tried to use the invalid file handle.

>  AttributeError: 'NoneType' object has no attribute 'read'

This is the one of which I was thinking.  So you see this error at the
end of a (long) traceback, and try to figure out where along the (long)
line of function calls I typed the wrong name.  Currently, the very end
of the traceback points you right at the bad code and says "NameError:
name 'filehandle' is not defined," which tells me (very nearly) exactly
what I did wrong.

> If the error was filehundle.close()  you will get:

s/u/a/

;-)

> I don't think any of those would be hard to find.

I guess it depends on how long your traceback is and how big those
functions are.  Also, from the Zen:

Explicit is better than implicit.

although from previous threads, we know that every pythonista has his or
her own definitions of "explicit" and "implicit."

Regards,
Dan

-- 
Dan Sommers

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


The GIL, callbacks, and GPFs

2005-07-06 Thread Francois De Serres
Hello,

I'm chasing a GPF in the interpreter when running my extension module.
It's not very elaborated, but uses a system (threaded) callback, and 
therefore the GIL.
Help would be mucho appreciated. Here's the rough picture:

win32_spam.c

/* code here is unit-tested OK */

typedef struct Bag {
char data[128];
site_t size;
} Bag;
typedef void (*PCallback)(const Bag * const bag);

Bag bag;
PCallback user_callback = NULL;

/* called by windoz */
static void CALLBACK win32_call_me(void) {
memcpy(bag.data, somestuff, 100);
bag.size = 100;
SPAWN_THREAD(user_callback, & bag);//pseudo-code
}



spam_module.c
-
/* most of the code here is pasted from doc */

static PyObject * my_callback = NULL;

static PyObject *
setCallback(PyObject *dummy, PyObject *args) {
PyObject *result = NULL;
PyObject *temp;
if (PyArg_ParseTuple(args, "O:miSetCallback", &temp)) {
if ((temp != Py_None) && (!PyCallable_Check(temp))) {
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
return NULL;
}
Py_XINCREF(temp);
Py_XDECREF(my_callback);
my_callback = temp;
Py_INCREF(Py_None);
result = Py_None;

/* set the actual callback in win32_spam.c */
user_callback = & external_callback;
}
return result;
}

static void external_callback(const Bag * const bag) { 
if (my_callback && (my_callback != Py_None)) {
PyObject * arglist = NULL;
PyObject * result = NULL;
arglist = Py_BuildValue("(s#)", bag->data, bag->size);

/* do it */
PyGILState_STATE gil = PyGILState_Ensure();
result = PyEval_CallObject(my_callback, arglist);
PyGILState_Release(gil);

Py_DECREF(arglist);
Py_DECREF(result);
}
}


blowup_spam1.py
-
# This throws a GPF on callback.
# Why, since the GIL is acquired by the callback?

import spam.py

def callback(stuff):
print stuff

if __name__ == '__main__':
spam.setCallback(callback)
raw_input()


blowup_spam2.py
-
# This throws a GPF as well
# Why, since we're using a threadsafe queue?

import spam
import Queue

q = Queue.Queue()

def callback(stuff):
q.put(stuff)

if __name__ == '__main__':
spam.setCallback(callback)
while True:
print q.get()



nice_spam.py
-
# This works
# Why, since the rest did not?

import spam
import Queue
import threading

q = Queue.Queue()

def callback(stuff):
q.put(stuff)

def job():
while True:
print q.get()

if __name__ == '__main__':
spam.setCallback(callback)
t = threading.Thread(job)
t.start()
raw_input()



Please point me to what I'm doing wrong...

TIA,
Francois


PS: I've already submitted my issue under "(Win32 API) callback to 
Python, threading hiccups", but I guess it was poorly formulated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Scipy - Latex Annotations in plots

2005-07-06 Thread fortuneteller
Hello, 

I'm quite new to python and Scipy.
Anyway I want to use it to plot graphs.
Does anybody know if there is the possibility to use Latex in SciPy's
plotting functions like gplt?

Thanks for your help, 

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


Re: Avoiding NameError by defaulting to None

2005-07-06 Thread Scott David Daniels
Ron Adam wrote:
> Dan Sommers wrote:
>> Lots more hard-to-find errors from code like this:
>> filehandle = open( 'somefile' )
>> do_something_with_an_open_file( file_handle )
>> filehandle.close( )
> 
> If do_something_with_an_open_file() is not defined. Then you will get:
> TypeError: 'NoneType' object is not callable
> 
> 
> If "file_handle" (vs "filehandle") is None.  Then you will still get an 
> error as soon as you tried to use the invalid file handle.
Ah, but where you use it can now far from the error in the source.  The
None could get packed up in a tuple, stored in a dictionary, all manner
of strange things before discovering it was an unavailable value.  I
would love the time back that I spent chasing bugs when Smalltalk told
me (I forget the exact phrasing) "nil does not respond to message abc."
My first reaction was always, "of course it doesn't, this message is
useless."  You really want the error to happen as close to the problem
as possible.

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


Re: precision problems in base conversion of rational numbers

2005-07-06 Thread [EMAIL PROTECTED]


Raymond Hettinger wrote:
> [Terry Hancock]
> > > Needless to say, the conventional floating point numbers in Python
> > > are actually stored as *binary*, which is why there is a "decimal"
> > > module (which is new).
> > >
> > > If you're going to be converting between bases anyway, it probably
> > > makes little difference whether you are using the decimal module
> > > or not, of course.  You'll have the same problems the conventional
> > > float numbers do.
>
> Not really.  floats won't do because they may not have sufficient
> precision to differentiate rational values falling close the split
> between representable values in a given base.  The decimal module
> offers arbitrarily large precision for making sure the error-term is
> small enough to not make a difference.
>
>
>
> [Brian van den Broek]
> > Thanks. mensanator provided the actual formula for my case. I had a
> > "magic number" in my code by which I multiplied my desired level of
> > "number of places in the representation" to obtain the value for
> > decimal.getcontext.prec.
> >
> > mensanator wrote:
> >
> > > The value you want for x is log(17)/log(10) =
> > > 1.2304489213782739285401698943283
> >
> > where x was my "magic number". I've not had a chance to think it
> > through yet, but I feel confident that given the formula, I'll be able
> > to work out *why* that is the formula I need.
>
> That "formula" just gives a starting point estimate.  The required
> decimal precision may be much higher.  If the rational falls very close
> to the half-way point between two representable numbers, the
> calculation needs to be retried with increased precision until the
> split-point is definitive (when the error-term becomes less than the
> distance to the next representable value).
>
> For a simple example, convert both 10247448370872321 and
> 10247448370872319 from base ten to 4 digits of hex.  The calculations
> need to be carried out to 15 places of hex (or 17 places of decimal)
> just to determine whether the fourth hex digit is a 7 or 8:
>
> >>> hex(10247448370872321)
> '0x246801L'
> >>> hex(10247448370872319)
> '0x2467ffL'

I don't understand your simple example.

log(10)/log(16) = 0.83048202372184058696757985737235

Multiplying by the number of decimal digits (17) gives

14.11819440327128997844885757533

Rounding up to an integer digit count, we need need 15 hex digits.
Isn't that exactly what you concluded? Where does that 4 hex digit
stuff come from?

>
> For an example of using decimal with iteratively increasing precision,
> see the dsum() recipe at
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090 .
> 
> 
> Raymond

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


Re: inheriting file object

2005-07-06 Thread Jeremy Jones
Jeremy wrote:

>Hello all,
>   I am trying to inherit the file object and don't know how to do it.  I 
>need to open a file and perform operations on it in the class I am 
>writing.  I know the simple syntax is:
>
>class MyClass(file):
>   ...
>
>but I don't know how to make it open the file for reading/writing.  Can 
>anyone help me out with this?
>Thanks,
>Jeremy
>
>  
>
Something like this?  I put the following code in test_file.py:

class MyFile(file):
def doing_something(self):
print "in my own method"


And used it like this:

In [1]: import test_file

In [2]: f = test_file.MyFile("foobar.file", "w")

In [3]: f.write("foo\n")

In [4]: f.doing_something()
in my own method


But do you really need to subclass file, or can you just use a file 
instance in your class?


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


Re: inheriting file object

2005-07-06 Thread harold fellermann

On 06.07.2005, at 18:58, Jeremy wrote:

> Hello all,
>   I am trying to inherit the file object and don't know how to do it.  I
> need to open a file and perform operations on it in the class I am
> writing.  I know the simple syntax is:
>
> class MyClass(file):
>   ...
>
> but I don't know how to make it open the file for reading/writing.  Can
> anyone help me out with this?

just invoke file.__init__ inside your own init. if you don't need to do
any initializiation in myFile.__init__, just leave the method and
file.__init__ will be invoked automatically.

class myFile(file) :
def __init__(self,fname,mode="r") :
file.__init__(self,fname,mode)

for line in myFile('testfile') :
print line


- harold -

--
If your only tool is a hammer, every problem looks like a nail.
--

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


Re: frozenset question

2005-07-06 Thread George Sakkis
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote:

> On Wed, 06 Jul 2005 14:25:30 +0100, Will McGugan wrote:
> > No need for the 'premature optimization is the root of all evil' speech.
> > I'm not trying to optimize anything - just enquiring about the nature of
> > frozenset. If typing 'frozenset' over 'set' gave me a saving in time or
> > memory (even if tiny) I would favour immutable sets, where appropriate.
>
> Well, obviously the "premature optimization" speech just went in one ear
> and out the other. "Saving in time or memory" is what optimization is
> about. What did you think optimization means?
>
> set and frozenset have different functionality (one is mutable, the other
> is not) and use cases (you use one where you need to dynamically add and
> remove items from a set, and the other where you need to use a set as a
> key in a dictionary). In most cases, they aren't interchangable.

Well, they *may* be interchangable under some conditions, and that was
the OP's point you apparently missed. If you don't need to dynamically
modify a set and don't add sets as keys in dictionaries, you currently
have a choice; both frozenset and set will work. So all other things
being equal, it makes sense to ask about the relative performance if
the only 'evil' it may introduce can be rectified in a single import.

George

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


inheriting file object

2005-07-06 Thread Jeremy
Hello all,
I am trying to inherit the file object and don't know how to do it.  I 
need to open a file and perform operations on it in the class I am 
writing.  I know the simple syntax is:

class MyClass(file):
...

but I don't know how to make it open the file for reading/writing.  Can 
anyone help me out with this?
Thanks,
Jeremy

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


Re: Conditionally implementing __iter__ in new style classes

2005-07-06 Thread Bengt Richter
On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:

>I'm trying to implement __iter__ on an abstract base class while I don't
>know whether subclasses support that or not.
>Hope that makes sense, if not, this code should be clearer:
>
>class Base:
>def __getattr__(self, name):
>if name == "__iter__" and hasattr(self, "Iterator"):
>return self.Iterator
>raise AttributeError, name
>
>class Concrete(Base):
>def Iterator(self):
>yield 1
>yield 2
>yield 3
>
>The idea is that if a subclass of Base defines an 'Iterator' method,
>instances are iterable.  They are not iterable otherwise.
>
>The above gives the expected behaviour: iter(Base()) raises a
>"TypeError: iteration over non-sequence", and iter(Concrete()) returns a
>generator.
>
>If, however, I make Base a newstyle class, this will not work any
>longer.  __getattr__ is never called for "__iter__" (neither is
>__getattribute__, btw).  Probably this has to do with data descriptors
>and non-data descriptors, but I'm too tired at the moment to think
>further about this.
>
>Is there any way I could make the above code work with new style
>classes?
Will a property or custom descriptor do what you want? E.g.

 >>> class Base(object):
 ... def __getIter(self):
 ... if hasattr(self, "Iterator"):
 ... return self.Iterator
 ... raise AttributeError, name
 ... __iter__ = property(__getIter)
 ...
 >>> class Concrete(Base):
 ... def Iterator(self):
 ... yield 1
 ... yield 2
 ... yield 3
 ...
 >>> iter(Base())
 Traceback (most recent call last):
   File "", line 1, in ?
 TypeError: iteration over non-sequence
 >>> iter(Concrete())
 
 >>> list(iter(Concrete()))
 [1, 2, 3]

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


Re: Lisp development with macros faster than Python development?..

2005-07-06 Thread jayessay
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> I've been reading the beloved Paul Graham's "Hackers and Painters".
> He claims he developed a web app at light speed using Lisp and lots
> of macros.

That was the original "yahoo store".


> It got me curious if Lisp is inherently faster to develop complex
> apps in.

For complex applications IMO/E there is no question that it is.  But
that is due to a lot of reasons, not only macros.


> It would seem if you could create your own language in Lisp using
> macros that that would be quite an advantage

Here's the story.  It has long been known that "domain specific
languages" (DSL) are a significantly more potent means of producing
applications (or chunks of them) in their domains than any so called
"general purpose" language.  This is true even if the DSL is not a
particularly great piece of work.  There are several examples of this
that most everyone knows about (though they may not realize it), with
"regular expressions" and SQL being among the most obvious.

You can take this further to "application specific languages" (ASL)
which provide even more leverage (though even narrower focus).
Obvious examples of this sort of thing would include AutoCAD and the
"grammar languages" of LALR parser generators.

The reason these things are so much better (for what they do) than
hacking away in your general purpose language is that the abstractions
they provide are much closer to what you want to say.  They are much
more _declarative_ than procedural.  You say _what_ you want done,
instead of specifying a lot of how that will produce the what [1].

Lisp (by which I mean here Common Lisp) macros enable you to build
DSLs and ASLs directly into the base language.  This has several
advantages beyond what the DSLs/ASLs themselves bring; some obvious
ones being:

* You don't have to write lexers and parsers, that part is provided to
  you for "free" by the Lisp reader[2].  In particularly sophisticated
  cases you may need to alter the reader behavior (via the readtables)
  and/or build a code walker to analyze things.  But that would be
  several sigmas out of the norm.

* Better yet, you don't have to write backend code generators.  The
  expansion code of a macro just gets compiled by the Lisp compiler
  (typically an optimizing native code generator).

* The DSL/ASL code can be seamlessly used with the base language (and
  libraries) just like when you use proprietary class libraries you've
  built from within the base language.  Only here, you get a much
  higher level of abstraction and expressive power.  So, you can
  freely use a DSL/ASL where it applies (and get all its advantages),
  but can effortlessly move to the base language when stepping outside
  its focus.

* Better yet, in highly complex application scenarios you can have a
  number of DSLs/ASLs each bringing their own high expressive power
  and move freely among them and the base language.  This should all
  work naturally together in concert.

* Most idioms can be abstracted away and the bugs associated with them
  disappear as well.  You don't have to remember sequences of "right,
  in these cases I first have to do this, then I have to call this
  that and the next thing in this order, and finally make sure I end
  it all with this bit over here."



Their are a few standard red herings trotted out against all this.
For example, "you mean you have a different programming language for
each application!  That's awful." or some variant.

If you think about it for a moment, this is complete nonsense.  Why?
Because you need to do this anyway - building and learning a set of
class libraries for an applicaion or domain (along with all its idioms
as well) is actually much more work, more painful, and (typically)
buys you less.  The point is, you need to learn the "vocabulary" of
application or domain code whether or not you use DSLs/ASLs.  Worse,
without the DSL/ASL approach you also need to learn a number of idioms
of how to _procedurally_ make use of the resources to achieve _what_
you want.

Another red hering goes something like: "it is much harder to learn a
DSL/ASL than to simply use your base general purpose language".  Most
programmer types espousing this are really weird, because in the next
breath they will be extolling the virtues of regular expressions, or
list comprehension or some other DSL that just happens to already be
embedded in their favorite language.  Also, it makes no sense anyway -
DSLs and ASLs are exactly the kind of thing provided to lay people at
the user end of many application scenarios.  Are they really somehow
that much superior to learning these things than programmers?

Another one is "fragmentation".  This is really a kind of variant on
the first, but it is used so often that it deserves its own mention.
Basically the argument is that if you build DSLs and ASLs eventually
your base language "fragments" and you have a few dozen languages
instead.  A few seconds thoug

Re: Tkinter grid layout

2005-07-06 Thread Richard Lewis

On Wed, 06 Jul 2005 16:32:42 GMT, "William Gill" <[EMAIL PROTECTED]>
said:
> Excuse me for intruding, but I followed examples and ended up with a 
> similar architecture:
> 
>  from Tkinter import *
>  class MyMain(Frame):
>  def __init__(self, master):
>  self.root = master
>  self.master=master
>  root = Tk()
>  app = MyMain(root)
>  app.master.title("Object Editor")
>  root.mainloop()
> 
> Erick, are you saying it should be modified to something like :
> 
>  from Tkinter import *
>  class MyMain(Tk):
>  ...
>  ...
>  app = MyMain()
>  app.title("My App")
>  app.mainloop()
> 
This is what I've got now, and it works. I don't think I've seen many
examples which inherited from Tk, but it certainly solved my problem.
And I see the logic in it: Tk is the main window of an application,
while Frame is, as Eric said, just a generic container.

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


Re: website catcher

2005-07-06 Thread Michael Ströder
jwaixs wrote:
> I need some kind
> of database that won't exit if the cgi-bin script has finished. This
> database need to be open all the time and communicate very easily with
> the cgi-bin framwork main class.

Maybe long-running multi-threaded processes for FastCGI, SCGI or similar
is what you're looking for instead short-lived CGI-BIN programs forked
by the web server.

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


  1   2   3   >