Re: Nimrod programming language

2009-05-09 Thread kay
On 8 Mai, 17:48, Andreas Rumpf  wrote:
> Dear Python-users,
>
> I invented a new programming language called "Nimrod" that combines Python's 
> readability with C's performance. Please check it out:http://force7.de/nimrod/
> Any feedback is appreciated.
>
> Regards,
> Andreas Rumpf
>
> __
> GRATIS für alle WEB.DE-Nutzer: Die maxdome Movie-FLAT!
> Jetzt freischalten unterhttp://movieflat.web.de

On a first impression it looks quite pleasant to me, your new
language! Two obvious questions on a Python list.

1) How to interface with Nimrod from Python?
2) Lack of typed hash-tables. Is this one of those particular features
that are planned to be implemented in version 0.80 and summarized
under "generic containers"?
--
http://mail.python.org/mailman/listinfo/python-list


Re: php to python code converter

2009-05-10 Thread kay
On 8 Mai, 17:19, Pascal Chambon  wrote:
> Hello
>
> That's funny, I was precisely thinking about a php to python converter,
> some weeks ago.
> Such a tool, allowing for example to convert some CMS like Drupal to
> python, would be a killer app, when we consider the amount of php code
> available.
>
> But of course, there are lots of issues that'd have to be fixed :
> - translating the php syntax to python syntax
> - forcing scope limitations where php doesn't have any
> - handling differences in semantics (for example, the booleanness of "0"
> or)
> - handling the automatic variable creation and coertion that php features
> - handling the php types like arrays (which are neither python lists nor
> python dicts)
> - providing a whole mirror of the php stdlib (string and file functions,
> access to environment vars...)

Some thoughts.

1) Syntax. Not a big deal.

2) Semantics. My favourite approach was to create a Python framework
that represents PHP in Python and enables round-trips. So one could
translate forth and back. Python code that is compliant to the
conventions of the framework can also be translated to PHP and for
each PHP program P following equation holds:

   py2php(php2py(P)) = P

This makes readable code mandatory.

3) PHP stdlib via C bindings ( ctypes? )

4) Corner cases of bindings: cut them off. Not everything has to be
translated. But produce stubs that raise NotImplementedError
exceptions.

Same arguments apply to Javascript. Not sure about Ruby but I do think
a parser is feasible despite context sensitivities. Ruby is not my
concern though.

Personally I'd be interested in Wordpress which I like and use.

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


Re: Nimrod programming language

2009-05-11 Thread kay
On 12 Mai, 02:10, Tomasz Rola  wrote:
> On Mon, 11 May 2009, [email protected] wrote:
> > > One question I ask myself upon seeing a new language is if it is possible
> > > to program amb (amb=ambiguous) operator in it. This page gives a very
> > > nice, "code first" explanation of amb and how it is supposed to work:
>
> > >http://www.randomhacks.net/articles/2005/10/11/amb-operator
>
> > Hm. I am not sure either. To me, it looks like a constraint solver by
> > using brute force.
>
> Yes, kind of. From what I understand [1], it's goal is to simulate
> nondeterministic "get right answer in one try", only this "one try"
> requires browsing the solution space (because we have only "classic"
> hardware). It is easy to use amb in wrong way, but I can see some cases
> when I would like it.

In Python you can use a generator expression. Dan Piponis example can
be stated as

g = ((i,j) for i in range(2,100) for j in range(2,i) if i*j == 481)

which doesn't require any call/cc hacks but is a deterministic "get
right in one try". Once Nimrod has coroutines it's just a matter of
sugaring them into comprehensions.

>
> [1] John McCarthy's paper still waits to be read by me, so... Ok, I have
> just had a look at it and it seems that Ruby implementation is a bit
> primitive compared to original concept. But still, this is what would be
> needed in most real life cases, I suppose.
>
> I think ability to define amb would allow me to write more concise code.
> As far as I can tell, this kind of stuff plays more and more important
> role in my programing.
>
> > It seems to require continuations. AFAIK
> > continuations are extremely hard to implement efficiently, so probably
> > it won't be done in Nimrod.
>
> Pity, a little. But not really big problem for me. Nimrod may be
> interesting anyway, time will tell :-).
>
> Regards,
> Tomasz Rola
>
> --
> ** A C programmer asked whether computer had Buddha's nature.  **
> ** As the answer, master did "rm -rif" on the programmer's home**
> ** directory. And then the C programmer became enlightened...  **
> ** **
> ** Tomasz Rola  mailto:[email protected] **

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


Re: Parsing Strings in Enclosed in Curly Braces

2009-05-15 Thread kay
On 15 Mai, 18:12, [email protected] wrote:
> How do you parse a string enclosed in Curly Braces?
>
> For instance:
>
> x = "{ABC EFG IJK LMN OPQ}"
>
> I want to do x.split('{} ') and it does not work. Why does it not work
> and what are EXCEPTIONS to using the split method?
>
> That I want to split based on '{', '}' and WHITESPACE.
>
> Please advise.
>
> Regards,
> Xav

import string
ttable   = string.maketrans("{} ", "\1\1\1")
print x.translate(ttable).split("\1")   # -> ['', 'ABC', 'EFG', 'IJK',
'LMN', 'OPQ', '']

The validity of the translation+split depends on the presence of \1 in
the original string of course.

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


issue

2019-07-10 Thread joshua kay
Hello,
i am encountering a issue with python 3.7.2rc1 64 bit currently
My operating system is windows 10 and every time i try to run my code the
shell just says:
== RESTART: C:\Users\joshu\OneDrive\Desktop\python\projects\multi choice.py
==

I how scanned the internet looking for a solution until i was made aware by
the python installer about the support team, please tell me a solution for
my issue

thank you,
Joshua kay
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Parametric Polymorphism

2005-09-26 Thread Kay Schluehr

Catalin Marinas wrote:
> Hi,
>
> Sorry if this was previously discussed but it's something I miss in
> Python. I get around this using isinstance() but it would be cleaner
> to have separate functions with the same name but different argument
> types. I think the idea gets quite close to the Lisp/CLOS
> implementation of methods.

Guido himself addressed multimethods in his Artima blog:

http://www.artima.com/weblogs/viewpost.jsp?thread=101605

See also the subsequent discussion about subtyping problems. 

Kay

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


Re: Will python never intend to support private, protected and public?

2005-09-28 Thread Kay Schluehr

Steve Holden wrote:
> could ildg wrote:
> > Python is wonderful except that it has no real private and protected
> > properties and methods.
> > Every py object has dict so that you can easily find what fields and
> > methods an obj has,
> > this is very convenient, but because of this, py is very hard to support
> > real private and
> > protected?
> > If private and protected is supported, python will be perfect.
> >
> You only say that because you assume private and protected give you a
> security that they actually don't. They certainly make it more difficult
> to *spot* the security errors.

Honestly I like to use private/protect/public modifiers in C++ for the
sake of code documentation. I like to know which attributes are
dedicated to be known by other objects, which ones are for internal use
only and which ones should be at least publicly accessible within a
class hierarchy. This helps structuring code in the large and spotting
attention. Code becomes easier accessible. But if we have Sunday or I
get asked by serious programmers I also know the right technical
answers about protection rights, security etc.

Kay

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


Re: Moronicity Xha Lee, Jargonizer

2005-09-29 Thread Kay Schluehr
Raymond Hettinger wrote:
> James Stroud wrote:
> > There needs to be an email filter that, when a thread is begun by a specific
> > user . . . it cans every
> > message in that thread.
>
> The tried-and-true solution is both simple and civil, "Don't feed the
> trolls."
>
>
> Raymond

People like very much responding on offense. But they seem not to like
liking that.

By the way I noticed also a few reasonable non-troll postings of Xah
without any response in the forum. Not even Xahs posting strategy is
coherent.

Kay

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


Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-08 Thread Kay Schluehr
Alex Martelli wrote:

> try it (and read the Timbot's article included in Python's sources, and the
> sources themselves)...

Just a reading advise. The translated PyPy source
pypy/objectspace/listsort.py might be more accessible than the
corresponding C code. 

Kay

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


Re: How to delete yourself????

2005-10-14 Thread Kay Schluehr

[EMAIL PROTECTED] wrote:
> Hello,
>
>
> I got a problem deleting objects, which are placed in a hirarchy
>
> Asume we have the following code:
> 
> class parent:
>
> MyChilds = [] # this list is filled with childs
>
> def AddChild(self, child):
> # add childs here, however this is done, it's not the point...
> child.MyParent = self
>
> def RemoveChild(self, child):
> # delete child from the list the way this is done is not
> our
> # problem here
>
>
> class child:
>
> MyParent = 0
>
> def deleteMe(self):
> MyParent.RemoveChild(self)
> ##

Please help me understand the child class. It does not make much sense
to me at all.

Why is it not sufficient to call child.parent.remove(child) if the
caller holds a child object but not the parent? Otherwise it should be
sufficient to call parent.remove(child). 

Kay

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


Re: object inheritance and default values

2005-10-14 Thread Kay Schluehr

George Sakkis wrote:
> "Ron Adam" <[EMAIL PROTECTED]> wrote:
>
> > I'm trying to implement simple svg style colored complex objects in
> > tkinter and want to be able to inherit default values from other
> > previously defined objects.
> >
> > I want to something roughly similar to ...
> >
> > class shape(object):
> >  def __init__(self, **kwds):
> >   # set a bunch of general defaults here.
> >   self.__dict__.update(kwds)
> > def draw(self, x=0, y=0, scale=1.0):
> >   # draw the object
> >
> > hello = shape(text='hello')
> > redhello = hello(color='red')
> > largeredhello = redhello(size=100)
> > largeredhiya = largeredhello(text='Hiya!')
> > largeredhiya.draw(c, 20, 50)
> >
> >
> > I think this will need to require __new__ or some other way to do it.
> > But I'm not use how to get this kind of behavior.  Maybe the simplest
> > way is to call a method.
> >
> > redhello = hello.makenew( color='red' )
>
> Just name it '__call__' instead of makenew and you have the syntax sugar you 
> want:
>
> def __call__(self, **kwds):
> new = self.__class__(**self.__dict__)
> new.__dict__.update(kwds)
> return new
>
> Personally I would prefer an explicit method name, e.g. 'copy'; hiding the 
> fact that 'shape' is a
> class while the rest are instances is likely to cause more trouble than it's 
> worth.
>
> George

Symmetry can be achieved by making shape a factory function of Shape
objects while those Shape objects are factory functions of other Shape
objects by means of __call__:

def shape(**kwds):
class Shape(object):
  def __init__(self,**kwds):
  self.__dict__.update(kwds)

  def __call__(self, **kwds):
  new = self.__class__(**self.__dict__)
  new.__dict__.update(kwds)
  return new

return Shape(**kwds)

Kay

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


Re: can a cut-down Python still be Python?

2005-10-17 Thread Kay Schluehr
The Eternal Squire wrote:

> My main question regarding this is:  even if I am successful, would the
> results be rejected out of hand by y'all as not meeting the Zen of
> Python?

Have you ever asked a Zen master about Zen?

Kay

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


Re: override a property

2005-10-18 Thread Kay Schluehr
Robin Becker wrote:
> Is there a way to override a data property in the instance? Do I need to 
> create
> another class with the property changed?
> --
> Robin Becker

It is possible to decorate a method in a way that it seems like
property() respects overridden methods. The decorator cares
polymorphism and accesses the right method.

def overridable(f):
def __wrap_func(self,*args,**kwd):
func = getattr(self.__class__,f.func_name)
if func.func_name == "__wrap_func":
return f(self,*args,**kwd)
else:
return func(self,*args,**kwd)
return __wrap_func


class A(object):
def __init__(self, x):
self._x = x

@overridable
def get_x(self):
return self._x

x = property(get_x)

class B(A):

def get_x(self):
return self._x**2

class C(B):pass

>>> a = A(7)
>>> a.x
7
>>> b = B(7)
>>> b.x
49
>>> c = C(7)
>>> c.x
49

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


Re: override a property

2005-10-20 Thread Kay Schluehr
Robin Becker wrote:

> I thought that methods were always overridable.
> In this case the lookup on the
> class changes the behaviour of the one and only property.

How can something be made overridable that is actually overridable? I
didn't know how to better express the broken polymorphism of Pythons
properties than by stating it as a pleonasm about the used get and set
methods. This way a property don't ever have to be redefined in
subclasses if get_x, set_x etc. are changed. 

Kay

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


Re: override a property

2005-10-22 Thread Kay Schluehr
Robin Becker wrote:
> Kay Schluehr wrote:
> > Robin Becker wrote:
> >
> >
> >>I thought that methods were always overridable.
> >>In this case the lookup on the
> >>class changes the behaviour of the one and only property.
> >
> >
> > How can something be made overridable that is actually overridable? I
> > didn't know how to better express the broken polymorphism of Pythons
> > properties than by stating it as a pleonasm about the used get and set
> > methods. This way a property don't ever have to be redefined in
> > subclasses if get_x, set_x etc. are changed.
> >
> > Kay
> >
>
> well I guess that's the ambiguity of human language. Clearly when I
> assign to a normal attribute I am changing its value; assigning to a
> property or descriptor does something that is not so obvious. Changing
> the behaviour of such an attribute could be done by inheritance as
> suggested. The new class has overridden the property. When I want to do
> that on an instance I have first to create a mutable version of the
> descriptor where the mutability is on the instance not the class. I call
> the action of changing the base descriptor behaviour 'overriding', but
> perhaps that's not the correct word. What do you suggest?
> --
> Robin Becker

I would suggest to take a step back and start with Raymond Hettingers
descriptor definition:

"In general, a descriptor is an object attribute with "binding
behavior", one whose attribute access has been overridden by methods in
the descriptor protocol. Those methods are __get__, __set__, and
__delete__. If any of those methods are defined for an object, it is
said to be a descriptor."

http://users.rcn.com/python/download/Descriptor.htm

The definition is a little confusing since we have to identify the
descriptor object that implements one of the descriptor methods
__get__, __set__ and __del__ with an object attribute that is assigned
by the descriptor ( as object not attribute ). Otherwise we can assert
that a descriptor becomes effective only if it is used as an object
attribute. The meaning / essence of a descriptor is to assign
attributes by a descriptor to alter binding behaviour but it's
essentially an object that can be handled quite differently. To make
the destinction clear I will talk about "descripted" attributes.

Now we can talk unambigously about "overriding" the descriptor by means
of overriding the descriptor methods in subclasses. In case of
"properties" we pass certain functions into property() that will be
wrapped into descriptor methods. Thereby property() is itself a
descriptor. If we use methods of the class where the descripted
attribute is defined, overriding has no effect on the descriptor. The
inheritance hierarchies of descriptors and classes that define
descripted attributes do not correspond.

One way of establishing a pseudo-correspondence I've already presented.
But maybe one can do it better without decorators? Remember that
property() is a descriptor factory and there is no intrinsic need to
pass functions into a factory function. Why not passing strings that
are names of methods?

For brevity only __get__ should be defined here:

class described_by(object):
def __init__(self, fget=""):
assert isinstance(fget, str)
self.fget = fget

def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError, "unreadable attribute"
return getattr(obj.__class__, self.fget)(obj)


class A(object):
def __init__(self, x):
self._x = x

def get_x(self):
return self._x

x = described_by("get_x")

class B(A):
def get_x(self):
return self._x**2

>>> a = A(7)
>>> a.x
7
>>> b = B(7)
>>> b.x
49

Regards,
Kay

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


wxListbook layout problem

2005-10-25 Thread Kay Schluehr
Probably some of you know the amazing demo application for wxPython.
When you open the Listbook demo in the
Core Windows/Contols folder, replace there wx.LB_DEFAULT by wx.LB_RIGHT
and resize the main window the listbox on the right side moves into the
area of colored panel. This is a surprise to say the least. Has anyone
of the GUI specialists an idea how to fix this?

Kay

PS. I tried this on WinXP only.

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


Re: Getting Python Accepted in my Organisation

2005-11-03 Thread Kay Schluehr

Stefan Arentz wrote:
> Stuart Turner <[EMAIL PROTECTED]> writes:
>
> > I'm already using it for a ton of things - I want to try and get broader
> > acceptance in the organisation for it to be made and 'officially supported
> > product'.
>
> IMO that is what you need to communicate: 'already using it for a ton of
> things' and probably adding 'being more productive than with tool XYZ'
>
>  S.

It didn't work well in my case. I still use Python for "tons of things"
but it didn't change the attitudes of my co-workers towards learning a
new language. It just changed my status as a programmer inside of the
department. And remember: Python is still cutting edge as a language
but sub-standard when it comes to tool support i.e. you do not have to
introduce just a language but a different culture of programming as it
is common sense now. 

Kay

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


Re: how to present Python's OO feature in design?

2005-11-06 Thread Kay Schluehr
pcmanlin wrote:
> because i have a problem that python's oo feature is so great, but
> maybe when the project become larger, python's no-declaration cannot
> mapping the design to practice?
>
> I am not sure about it.

As far cartoon-ware ( UML ) is concerned note that it is NOT Pythons
non-declarativeness but it's dynamicity that makes it hard to picture
it's design. Classes in Python are cheap, object structures are even
cheaper. That's why UML hardly provides an adequate representation of
Python programs and Pythonistas usually don't care a lot about it.

Kay

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


Re: Proposal for adding symbols within Python

2005-11-17 Thread Kay Schluehr

Steven Bethard wrote:
> Pierre Barbier de Reuille wrote:
> > Proposal
> > 
> >
> > First, I think it would be best to have a syntax to represent symbols.
> > Adding some special char before the name is probably a good way to
> > achieve that : $open, $close, ... are $ymbols.
>
> How about using the prefix "symbol." instead of "$"?
>
>  >>> symbol.x

I recognize 3 symbols: a "symbol" a dot and another symbol. So I
wouldn't call this a symbol. Maybe a "diabolon"? Other languages have
symbols, Python has diaboli ;)

Kay

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


Re: Why are there no ordered dictionaries?

2005-11-21 Thread Kay Schluehr
Fredrik Lundh wrote:

> huh?  if you want a list, use a list.
>
> d = [('a', {...}), ('b', {})]

If one wants uniform access to a nested data structure like this one
usually starts writing a wrapper class. I do not think the requirement
is anyhow deeper than a standard wrapper around such a list ( as a
model ) but the implementation may be different with respect to optimal
time complexitiy of element access. But the interface of the wrapper
class of d might resemble that of a dict. While the interface is that
of a dict the implementation is closer to a nested list. An "ordered
dict" would lower the impedance between a dict and a list. 

Kay

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


Re: Why are there no ordered dictionaries?

2005-11-22 Thread Kay Schluehr
Christoph Zwerschke wrote:

> That would be also biased (in favour of Python) by the fact that
> probably very little people would look for and use the package in the
> cheese shop if they were looking for ordered dicts.

Does anyone actually use this site? While the Vaults offered a nice
place and a nice interface the Cheese Shop has the appeal of a code
slum. 

Kay

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


Re: Why are there no ordered dictionaries?

2005-11-22 Thread Kay Schluehr

A.M. Kuchling wrote:
> On 22 Nov 2005 01:41:44 -0800,
>       Kay Schluehr <[EMAIL PROTECTED]> wrote:
> > Does anyone actually use this site? While the Vaults offered a nice
> > place and a nice interface the Cheese Shop has the appeal of a code
> > slum.
>
> Looking at the Cheese Shop's home page at
> http://cheeseshop.python.org/pypi, which lists recent package updates,
> three packages were updated on 11/22, and three on 11/21.  Two on
> 11/20, six on 11/19 (someone was busy!).
>
> Looking at the Vaults's 'latest' page at
> http://py.vaults.ca/apyllo.py?a=l, two packages were updated on 08/23,
> and five on 08/06.
>
> What would improve the Cheese Shop's interface for you?
>
> --amk

>From the treasures of the vaults to cheese shops - an upside down
evolution :( Personally I find the usability of the Vaults quite well
and it's design o.k. I guess it is a technical detail that causes the
Vaults to be phased out.

If I'd try something more innovative by myself I'd think about
accessing and filtering packages through the Python console itself.
Probably an enhanced standard console enabling SQL commands. Updates of
a local database ( e.g. SQLite ) should be cheap and may be performed
by only one request. Searching, filtering, loading, installing would be
done in a Python+SQL environment. 

Kay

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


Re: Application Plugin Framework

2005-11-22 Thread Kay Schluehr
Ron wrote:
> Hello,
>
> I'm attempting to develop a  plugin framework for an application that I'm
> working on.  I wish to develop something in which all plugins exist in a
> directory tree.  The framework need only be given the root of the tree.  The
> framework then uses os.path.walk to search all for all files named
> 'plugin.pyc'.  These are then loaded using imp.load_compiled().  They need
> contain only one variable called 'plugin' which is a reference to an
> instance of the plugin object.  This is extrated from the loaded module
> using getattr.  After that, the plugins are easy to work with since they
> implement a standard interface.  Or so the theory goes.  And this does work
> fine provided the plugin is implemented entirely within that one file.  If
> there are support modules that the main plugin module imports, which exist
> in the plugin's directory, then I get problems.  The imports fail.  I get
> "ImportError:  No module named "
>
> Here's PluginManager.py:
> 
>
> import os
>
>
> class PluginManager( object ):
>def __init__( self, pluginDir ):
>   self._plugins = { }
>
>   os.path.walk( pluginDir, self._addPlugin, None )
>
>def _addPlugin( self, arg, dirname, names ):
>   import imp
>
>   for filename in names:
>  fullFilename = os.path.join( dirname, filename )
>  if os.path.isfile( fullFilename ) and (filename == 'plugin.pyc'):
> module = imp.load_compiled( 'plugin', fullFilename )
> self._plugins[ plugin.name ] = getattr( module, 'plugin' )
> return
>
> PM = PluginManager( r'C:\Personal\SWDev\ModuleTest' ) # Root of the
> plugin directory tree
>
> print 'Plugin List: ', PM._plugins.keys()
>
> for name,plugin in PM._plugins.iteritems():
>plugin.doSomething( )
>
> print 'done!'
>
> ###
> My plugin.py file is in C:\Personal\SWDev\ModuleTest\Plugins\MyPlugin.  It's
> called plugin.pyc (which I compiled from the following source by importing
> it into the interactive python shell.
> ###
>
> import work
>
>
> class MyPlugin( object ):
>def __init__( self ):
>   self.name  = 'MyPlugin'
>
>def doSomething( self ):
>   work.foo( )
>
>
> plugin = MyPlugin( )
>
> ###
> Finally, work.py is in the same directory as plugin.py
> ###
>
> def foo( ):
>print 'foo called'
>
> ##

Hi Ron,

the import directive does not lookup work.py in the same directory as
plugin.py. It searches through the directory of PluginManager.py and
otherwise searches through the directories of sys.path. The solution is
referencing work.py relative to the dir of the PluginManager.
MyFramework/
__init__.py
PluginManager.py
Plugins/
   plugin.py
   work.py


###
plugin.py
###
import MyFramework.Plugins.work as work

# do some stuff...

If import still causes trouble add the path of MyFramework to sys.path.


Regards,
Kay



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


Re: Why are there no ordered dictionaries?

2005-11-22 Thread Kay Schluehr
Bengt Richter wrote:
> On Mon, 21 Nov 2005 01:27:22 +0100, Christoph Zwerschke <[EMAIL PROTECTED]> 
> wrote:
>
> >Fredrik Lundh wrote:
> >> if you restructure the list somewhat
> >> d = (
> >> ('pid', ('Employee ID', 'int')),
> >> ('name', ('Employee name', 'varchar')),
> >> ('sal', ('Salary', 'float'))
> >> )
> >> you can still loop over the list
> >> ...
> >> but you can easily generate an index when you need it:
> >> index = dict(d)
> >
> >That's exactly the kind of things I find myself doing too often and what
> >I was talking about: You are using *two* pretty redundant data
> >structures, a dictionary and a list/tuple to describe the same thing.
> >Ok, you can use a trick to automatically create the dictionary from the
> >tuple, but still it feels somewhat "unnatural" for me. A "ordered
> >dictionary" would be the more "natural" data structure here.
> >

> But, as has been mentioned**n, this is only one example of an ordering one
> could make default for an "ordered" dictionary. Suppose you say it should
> be ordered by insertion order, so
>   d = OrderedDict(); d[1]='one'; d[2]='two' =>> list(d) => [1, 2]
> ok, now we do d[1]='ein' and what is the order? list(d) => [2, 1] ??
> Or do replacements not count as "insertions"?

"Insertion-order" is not a good term. For a dictionary {key:value} pair
creation, updating and deletion are possible modifying operations.  I
don't see how deletion influences the order so creation and updating
remains. Therefore you have to select beween a creation_order and an
update_order. This can be reduced to one additional keyword e.g.
"creation_order" that is assigned a boolean value which is true by
default.

> The devil is always going
> to be in the details. Maybe you want a model that works more like a list
> of key:value pairs with just optimized access to a pair by key name as
> well as position in the list. Or maybe you want to permit append and
> NOT prevent [('a',1), ('a':2)] and maybe d['a'] => [1, 2] ???

As far as I understand the requirement an odict provides the same
interface as a dict. The only difference is a certain order of the keys
that is induced by operations on a dict and cannot be established by
properties of the keys ( or values ) itself.

> Note that is isn't hard to snap a few pieces together to make an ordered
> dict to your own specs. But IMO it belongs in pyPI or such, not in the system
> library. At least until it gets a lot of mileage -- and MMV ;-)

It's also not very hard to write a hex2ascii converter. That's the
reason why 20 incompatible versions of it ( coded in C ) exists in my
department ;)

Kay

PS. Here is some attempt of my own to implement an odict, following the
discussion here.
The implementation highlights just the model and is incomplete:

class odict(dict):
def __init__(self, create_order = True):
dict.__init__(self)
self.create_order = create_order
self.__cnt = 0

def __setitem__(self, key, value):
val = dict.get(self,key)
if val and self.create_order:
dict.__setitem__(self, key, (val[0], value))
else:
self.__cnt+=1
dict.__setitem__(self, key, (self.__cnt, value))

def __getitem__(self, key):
return dict.__getitem__(self, key)[1]

def values(self):
return list(zip(*sorted(dict.values(self)))[1])

def keys(self):
ks = [(dict.get(self,k)[0],k) for k in dict.keys(self)]
return list(zip(*sorted(ks))[1])

>>> od = odict()
>>> od["a"] = 0
>>> od["b"] = 8
>>> od.keys()
["a", "b"]

>>> od = odict(create_order = False)
>>> od["a"] = 1
>>> od["b"] = 2
>>> od["a"] = 3
>>> od.keys()
["b", "a"]

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


Re: Why are there no ordered dictionaries?

2005-11-23 Thread Kay Schluehr

[EMAIL PROTECTED] wrote:
> Steve Holden wrote:
> > Perhaps now the answer top your question is more obvious: there is by no
> > means universal agreement on what an "ordered dictionary" should do.
> > Given the ease with which Python allows you to implement your chosen
> > functionality it would be presumptuous of the core developers to favour
> > any one of the several reasonable alternatives that might be chosen.
> >
> It seems to be though as "ordered dictionary" are slowly to be confined
> to only "ordered on order of change to the dictionary".

While I'm only +0 for a standard odict I'm wondering that discussing
this topic leads to the auctoritative conclusion that it is unsolvable,
we have to accept infinite diversity etc. where people like me seeing a
classification immediately ( mathematical education? ) . Of course this
matter is trivial but we already know about monster-threads revolving
around decorator syntax ( including hurt souls and semi-scientific
papers ) and abandoning the print statement in Python 3.0.

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


Re: user-defined operators: a very modest proposal

2005-11-23 Thread Kay Schluehr
Steve R. Hastings wrote:

> It should be possible to define operators using punctuation,
> alphanumerics, or both:
>
> ]+[
> ]add[
> ]outer*[

Seems like you look for advanced source-code editors.Some ideas are
around for quite a while e.g. here

http://en.wikipedia.org/wiki/Intentional_programming

I'm not sure if current computer algebra systems also offer a WYSIWYG
input mode? Of course this is not clutter and line noise but domain
specific standard notation.

There has also been a more Python related ambitious multi-language
project called Logix that enabled user-defined operators but it seems
to be dead.

Kay

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


Re: How to get started in GUI Programming?

2005-11-27 Thread Kay Schluehr

[EMAIL PROTECTED] wrote:
> I am trying to learn GUI programming in Python, but have to confess I
> am finding it difficult.

Don't do it if you can prevent it.

GUI - toolkits are very complex beasts and at least to me a source of
pain far more as a joy. Python cannot help you making them
significantly simpler but on the contrary add just another level of
indirection. Python normally shines when you have to glue libraries
together or programming simply Python scripts for a broad range of
purposes but if the wrapped library publishes a huge interface with
hundreds of classes and thousands of methods and attributes the benfit
of Pythons abstraction converges to zero. Python does not offer a good
toolchain to take up with Swing, WinForms or Qt to name just a few
delivered with IDEs that are very helpfull in developing GUI apps. Not
to talk about documentation...

Conclusion: if you are already familiar with BASIC I would just
continue writing BASIC apps using VisualBasic dotNet, Windows Forms as
the underlying GUI toolktit and VisualStudio as IDE. Forget the
coolness factor of the language. Cool people never care a lot what
other people think. If you finally want to glue assemblys/controls
together in Python this is still possible with IronPython or
Python-dotNet ( which is a CPython binding to the CLR, available at
Zope.org ).

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


Re: python speed

2005-11-30 Thread Kay Schluehr

Harald Armin  Massa wrote:
> Dr. Armin Rigo has some mathematical proof, that High Level Languages
> like esp. Python are able to be faster than low level code like
> Fortran, C or assembly.
>
> I am not wise enough to understand that proof.
>
> Maybe I understood those papers totally wrong and he was saying
> something totally different.

Here is a paper of Armin explaining his psycology:

http://psyco.sourceforge.net/theory_psyco.pdf

Heck, Python has at least one programmer who is computer scientist and
knows how to draw commutative diagrams :)

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


Python package installing rationale

2005-12-03 Thread Kay Schluehr
In almost any case I install a Python package via distutils some
directories in the package tree are left behind e.g. the docs,
licenses, tests etc. I wonder if there is some rationale behind this?
Should it be left to the "creative freedom" of the user to copy the
docs whereever she wants or is there a dedicated place for them and if
any why isn't it simple to declare it in the setup script?

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


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

2005-07-08 Thread Kay Schluehr


[EMAIL PROTECTED] schrieb:
> 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.

Yes, Paul is a postmodern hero who reininvents himself and his language
every day and with every program:

"Experienced Lisp programmers divide up their programs differently. As
well as top-down design, they follow a principle which could be called
bottom-up design-- changing the language to suit the problem. In Lisp,
you don't just write your program down toward the language, you also
build the language up toward your program. As you're writing a program
you may think "I wish Lisp had such-and-such an operator." So you go
and write it. Afterward you realize that using the new operator would
simplify the design of another part of the program, and so on. Language
and program evolve together."

http://www.paulgraham.com/progbot.html

Remark: The same may be claimed about Forth.

This might be a great self experience for some "great hackers" but just
annoying for others who used to work with modular standard librarys and
think that the border of the language and an application should be
somehow fixed to enable those. 

Kay

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


Re: f*cking re module

2005-07-08 Thread Kay Schluehr
jwaixs schrieb:
> arg... I've lost 1.5 hours of my precious time to try letting re work
> correcty.

1.5 hours are not enough for understanding regular expressions. But to
be honest: I never had the patience to learn them accurately and I
guess I will never do so as well as I don't ever learn sed or awk or
Perl. When my brain hit regexp syntax the first time I thought about
writing a little language that translates readable Python expressions
in awkward regexps as an intermediary language which gets finally
compiled into a finite state-machine descriptions. Fortunately I was
not the first one who considered his mental weakness/aesthetic
repulsion as a virtue:

http://home.earthlink.net/~jasonrandharper/reverb.py

I never took time for a critical review. The module just worked for my
purposes.

Kay

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


Re: removing list comprehensions in Python 3.0

2005-07-08 Thread Kay Schluehr
Steven Bethard schrieb:

> I think the jury's still out on this one:
>
> * Alex Martelli expects list comprehensions to be removed. [1]
> * Robert Kern wants list comprehensions removed. [2]
> * Raymond Hettinger encourages continued use of list comprehensions [3]
> * Jeremy Bowers thinks list comprehensions should stay. [4]
>
> I only searched a few relatively recent threads in c.l.py, so there are
> probably more, but it looks to me like the final decision will have to
> be made by a pronouncement from Guido.

Well, I want to offer a more radical proposal: why not free squared
braces from the burden of representing lists at all? It should be
sufficient to write

>>> list()
list()

After being free one can use them for other purposes e.g. replacing the
ugly @ decorator character by the lovely [ .. ] notation or other
important features no one never trusted to implement waiting for the
right syntax sugar. More than this round braces together with lists can
be considered as a concession to the LISP programmer who was repelled
from Python by the decision to eliminate functional programming
features. 

Kay

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


Re: removing list comprehensions in Python 3.0

2005-07-08 Thread Kay Schluehr


Leif K-Brooks schrieb:
> Kay Schluehr wrote:
> > Well, I want to offer a more radical proposal: why not free squared
> > braces from the burden of representing lists at all? It should be
> > sufficient to write
> >
> >>>>list()
> >
> > list()
>
> So then what would the expression list('foo') mean? Would it be
> equivalent to ['foo'] (if so, how would you convert a string or other
> iterable to a list under Py3k?), or would it be equivalent to ['f', 'o',
> 'o'] as it is in now (and is so, what gives?)?

Spiltting a string and putting the characters into a list could be done
in method application style:

>>> "abc".tolist()
list('a','b','c')

Or equivalent from lists point of view:

>>> list.from_str("abc")
list("a", "b", "c" )

Kay

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


Re: removing list comprehensions in Python 3.0

2005-07-08 Thread Kay Schluehr
Leif K-Brooks schrieb:
> Kay Schluehr wrote:
> >>>>list.from_str("abc")
> >
> > list("a", "b", "c" )
>
>
> I assume we'll also have list.from_list, list.from_tuple,
> list.from_genexp, list.from_xrange, etc.?

One might unify all those factory functions into a single
list.from_iter that dispatches to the right constructor that still
lives under the hood. More conceptually: there is some abstract iter
base class providing a from_iter method which may be overwritten in
concrete subclasses like tuple, str or list.

I would further suggest a lazy iterator used to evaluate objects when
they get accessed the first time:

>>> l = lazy( math.exp(100) , 27 )

>>> l[1]
27

The first element won't ever be evaluated if it does not get accessed
explicitely. This is some very special kind of partial
evaluation/specialization.

Kay

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


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

2005-07-09 Thread Kay Schluehr


Kirk Job Sluder schrieb:
> "Kay Schluehr" <[EMAIL PROTECTED]> writes:
>
> > This might be a great self experience for some "great hackers" but just
> > annoying for others who used to work with modular standard librarys and
> > think that the border of the language and an application should be
> > somehow fixed to enable those.
>
> In what way do lisp macros prevent the creation of modular libraries?
> Common Lisp does does have mechanisms for library namespaces, and in
> practice a macro contained within a library is not that much different
> from a function contained in a library or a class contained in a
> library. Macros just provide another mechanism for creating useful
> domain-specific abstractions.

To be honest I don't understand what a "domain-specific abstraction"
could be? What is the benefit of abstractions if they are not
abstracting from particular domain specific stuff?

> The primary advantage to macros is that
> you can create abstractions with functionality that is not easily
> described as either a function or a class definition.

As long as macros are used to create new language features such as an
object system like CLOS this technique may be perfectly justified for
language developers ( ! ) but I still consider it as a bad idea to
muddle the language development and the application development, that
seems to be the favourite programming style of Paul Graham. On the
other hand thinking about language development as a certain application
domain I find nothing wrong with the idea that it once reaches somehow
a state of a mature product that should not be altered in arbitrary
manner for the sake of a large user community.

Kay

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


Hosting Python projects

2005-07-09 Thread Kay Schluehr
Jacob Page schrieb:
> I have created what I think may be a useful Python module, but I'd like
> to share it with the Python community to get feedback, i.e. if it's
> Pythonic.  If it's considered useful by Pythonistas, I'll see about
> hosting it on Sourceforge or something like that.  Is this a good forum
> for exposing modules to the public, or is there somewhere
> more-acceptable?  Does this newsgroup find attachments acceptable?
>
> --
> Jacob

One side-question: has anyone made experiences in hosting his open
source project on 

http://www.python-hosting.com/

Regards,
Kay

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


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-09 Thread Kay Schluehr

Ralf W. Grosse-Kunstleve schrieb:
> My initial proposal
> (http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html) didn't
> exactly get a warm welcome...

Well ... yes ;)

Ralf, if you want to modify the class instantiation behaviour you
should have a look on metaclasses. That's what they are for. It is not
a particular good idea to integrate a new method into the object base
class for each accidental idea and write a PEP for it.

I provide you an example which is actually your use case. It doesn't
change the class hierarchy : the metaclass semantics is not "is a" as
for inheritance but "customizes" as one would expect also for
decorators.

class autoattr(type):
'''
The autoattr metaclass is used to extract auto_xxx parameters from
the argument-tuple or the keyword arguments of an object
constructor __init__
and create object attributes mit name xxx and the value of auto_xxx
passed
into __init__
'''
def __init__(cls,name, bases, dct):
super(autoattr,cls).__init__(name,bases,dct)
old_init = cls.__init__
defaults = cls.__init__.im_func.func_defaults
varnames = cls.__init__.im_func.func_code.co_varnames[1:]

def new_init(self,*args,**kwd):
for var,default in zip(varnames[-len(defaults):],defaults):
if var.startswith("auto_"):
self.__dict__[var[5:]] = default
for var,arg in zip(varnames,args):
if var.startswith("auto_"):
self.__dict__[var[5:]] = arg
for (key,val) in kwd.items():
if key.startswith("auto_"):
self.__dict__[key[5:]] = val
old_init(self,*args,**kwd)
cls.__init__ = new_init

class app:
__metaclass__ = autoattr
def __init__(self, auto_x, y, auto_z = 9):
pass

>>> a = app(2,5)
>>> a.x
2
>>> a.z
9
>>> a.y
-> AttributeError


Kay

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


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-09 Thread Kay Schluehr
 > I stripped your code down to the essence. See attachment.
> For the user your approach then becomes:
>
>   class grouping:
> __metaclass__ = autoattr
> def __init__(self, x, y, z):
>   pass

No. This is clearly NOT what I had in mind. I translated your original
proposal which introduced a punctuation syntax '.x' for constructor
parameters forcing the interpreter to create equally named object
attributes into a naming convention that can be handled by a metaclass
customizer. The grouping.__init__ above does exacly nothing according
to my implementation. I would never accept dropping fine-tuning
capabilities. The "auto_" prefix is all the declarative magic.

> My __autoinit__ suggestion would result in (assuming object supports
> this by default):
>
>   class grouping(object):
> def __autoinit__(self, x, y, z):
>   pass
>
> I think that's far more intuitive.

Being intuitive is relative to someones intuition. 

Kay

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


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-10 Thread Kay Schluehr
Dan Sommers schrieb:

> How about this:
>
> def __init__(self, self.x, y, self.z):
> # self.x, self.z from first and third explicit parameters
> do_something_with_y()

Can you tell me in which way it is anyhow better than the original
proposal

 def __init__(self, .x, y, .z):
  # self.x, self.z from first and third explicit parameters
  do_something_with_y()

besides that it is more verbose? 

Kay

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


Re: __autoinit__ (Was: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code)

2005-07-11 Thread Kay Schluehr
Reinhold Birkenfeld schrieb:
> Kay Schluehr wrote:
> > Dan Sommers schrieb:
> >
> >> How about this:
> >>
> >> def __init__(self, self.x, y, self.z):
> >> # self.x, self.z from first and third explicit parameters
> >> do_something_with_y()
> >
> > Can you tell me in which way it is anyhow better than the original
> > proposal
> >
> >  def __init__(self, .x, y, .z):
> >   # self.x, self.z from first and third explicit parameters
> >   do_something_with_y()
> >
> > besides that it is more verbose?
>
> It is more explicit. Explicit is better than implicit.

The punctuation syntax makes it explicit too. But maybe a point is a
more tiny and less explicit symbol than an @ that makes a decorator
explicit ;)

> But as with many proposals, this raises consequential questions, for
> example, how "self.x" parameters are handled in other methods, or even
> functions, as __init__ is not special-cased by the parser.
>
> Reinhold

Yes. My argument against the syntax is more that of a language lawyer:
how a class uses the argument parameters of a constructor is an
implementation detail of a class and should not be published in the
constructor interface.

One may assign special attributes to the classes ( e.g. tagging it with
a metaclass ) or a qualifier. I had recently a look on Scala an
object-functional language running on top of the JVM. Scala introduces
the concept of a "case class" to represent object trees. All arguments
passed into a case class constructor become automagically object
attributes. This is for convenience and let the tree grow if the passed
arguments are case class instances again. Here it is the class type
that determines how it's construction is handled. I think this is a
reasonable approach. 

Kay

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


Re: decorators as generalized pre-binding hooks

2005-07-11 Thread Kay Schluehr
George Sakkis schrieb:

> > 1. classes have metaclasses, functions don't have metafunctions.  No one
> > gave an example for classes not handled at least as well with a metaclass.
>
> Would something like the following count ?
>
> @abstractclass
> class AbstractFrame(object):
>
> @abstractclass
> @innerclass
> class AbstractPanel(object):
> pass
>
> For one thing, it's more readable than the respective __metaclass__
> declarations. Moreover, stacking two or more decorators is
> syntactically straightforward, while for metaclasses you have to write
> boilerplate code for making a subclass of the components, e.g.:
> class AbstractInnerClass(AbstractClass, InnerClass): pass
> Fortunately metaclasses are not that commonly used to cause
> combinatorial explosion of such boilerplate classes.

I think it would be a good idea to pronounce the similarity between
function decorators and metaclasses. Metaclasses were once introduced
as an arcane art of fuzzy bearded hackers or supersmart 'enterprise
architects' that plan at least products of Zope size but not as a tool
for the simple programmer on the street. But maybe they should be and
there should also be librarys of them representing orthogonal
customizations ready for plug in.

Since metaclasses follow an "adapt", "customize" or "decorate"
semantics it is a good idea not to use inheritance to stack them which
implies that one metaclass refines an other.

+1 for metaclasses as class decorators.

Kay

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


Re: decorators as generalized pre-binding hooks

2005-07-11 Thread Kay Schluehr


Christopher Subich schrieb:
> Kay Schluehr wrote:
> > I think it would be a good idea to pronounce the similarity between
> > function decorators and metaclasses. Metaclasses were once introduced
> > as an arcane art of fuzzy bearded hackers or supersmart 'enterprise
> > architects' that plan at least products of Zope size but not as a tool
> > for the simple programmer on the street. But maybe they should be and
> > there should also be librarys of them representing orthogonal
> > customizations ready for plug in.
>
> In which case, I point out the need for better, more accessible
> documentation.  The Python 2.4 tutorial, for example, doesn't mention
> them at all as far as I've noticed.

That's true also for properties and decorators - the latter may be
excused because they are new in Python 2.4. There are a few good
documents out there explaining advanced stuff e.g. mro and descriptors.
Maybe those texts should be delivered with the doc and linked from the
tutorial as "further reading"? But maybe the whole document structure
could be redesigned providing a Wikipedia style with seperated but
linked articles, example code etc. ?

Kay

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


Ordering Products

2005-07-17 Thread Kay Schluehr
Here might be an interesting puzzle for people who like sorting
algorithms ( and no I'm not a student anymore and the problem is not a
students 'homework' but a particular question associated with a
computer algebra system in Python I'm currently developing in my
sparetime ).

For motivation lets define some expression class first:

class Expr:
def __init__(self, name=""):
self.name = name
self.factors = [self]

def __mul__(self, other):
p = Expr()
if isinstance(other,Expr):
other_factors = other.factors
else:
other_factors = [other]
p.factors = self.factors+other_factors
return p

def __rmul__(self, other):
p = M()
p.factors = [other]+self.factors
return p

def __repr__(self):
if self.name:
   return self.name
else:
   return "*".join([str(x) for x in self.factors])

One can create arbitrary products of Expr objects ( and mixing numbers
into the products ):

>>> a,b,c = Expr("a"),Expr("b"),Expr("c")
>>> a*b
a*b
>>> 7*a*8*9
7*a*8*9

The goal is to evaluate such products and/or to simplify them.

For expressions like

>>> x = 7*a*8*9

this might be easy, because we just have to sort the factor list and
multiply the numbers.

>>> x.factors.sort()
>>> x
a*7*8*9

-> a*504

This can be extended to arbitrary products:

>>> x = 7*a*b*a*9
>>> x.factors.sort()
>>> x
a*a*b*7*9

-> (a**2)*b*63

Now lets drop the assumption that a and b commute. More general: let be
M a set of expressions and X a subset of M where each element of X
commutes with each element of M: how can a product with factors in M be
evaluated/simplified under the condition of additional information X?

It would be interesting to examine some sorting algorithms on factor
lists with constrained item transpositions. Any suggestions?

Regards,
Kay

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


Re: Ordering Products

2005-07-17 Thread Kay Schluehr
Diez B.Roggisch wrote:
> Kay Schluehr  gmx.net> writes:
>
> > Now lets drop the assumption that a and b commute. More general: let be
> > M a set of expressions and X a subset of M where each element of X
> > commutes with each element of M: how can a product with factors in M be
> > evaluated/simplified under the condition of additional information X?
> >
> > It would be interesting to examine some sorting algorithms on factor
> > lists with constrained item transpositions. Any suggestions?
>
> I don't think that sorting is the answer here.
> Firts of all IMHO you have to add an
> additional constraint -  associativity of the operation in question
>  So the problem could  be reduced to making the constant
> parts be more associative than the non-constant parts.
> which you should be able to
> do with a parser.

Hi Diez,

I have to admit that I don't understand what you mean with the
'constant parts' of an expression?

The associativity of __mul__ is trivially fullfilled for the dummy
class M if an additional __eq__ method is defined by comparing factor
lists because those lists are always flat:

def __eq__(self, other):
if isinstance(other,M):
return self.factors == other.factors
return False

The sorting ( or better 'grouping' which can be represented by sorting
in a special way ) of factors in question is really a matter of
(non-)commutativity. For more advanced expressions also group
properties are important:

If a,b are in a center of a group G ( i.e. they commute with any
element of G ) and G supplies an __add__ ( besides a __mul__ and is
therefore a ring ) also a+b is in the center of G and (a+b)*c = c*(a+b)
holds for any c in G.

It would be nice ( and much more efficient ) not to force expansion of
the product assuming distributivity of __add__ and __mul__ and
factorization after the transposition of the single factors but
recognizing immediately that a+b is in the center of G because the
center is a subgroup of G.


Regards,
Kay

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


Re: Ordering Products

2005-07-17 Thread Kay Schluehr


Ron Adam wrote:
> Kay Schluehr wrote:
> > Here might be an interesting puzzle for people who like sorting
> > algorithms ( and no I'm not a student anymore and the problem is not a
> > students 'homework' but a particular question associated with a
> > computer algebra system in Python I'm currently developing in my
> > sparetime ).
>
> 
>
> >>>>x = 7*a*b*a*9
> >>>>x.factors.sort()
> >>>>x
> >
> > a*a*b*7*9
> >
> > -> (a**2)*b*63
> >
> > Now lets drop the assumption that a and b commute. More general: let be
> > M a set of expressions and X a subset of M where each element of X
> > commutes with each element of M: how can a product with factors in M be
> > evaluated/simplified under the condition of additional information X?
> >
> > It would be interesting to examine some sorting algorithms on factor
> > lists with constrained item transpositions. Any suggestions?
> >
> > Regards,
> > Kay
>
> Looks interesting Kay.

I think so too :) And grouping by sorting may be interesting also for
people who are not dealing with algebraic structures.

> I think while the built in sort works as a convenience, you will need to
> write your own more specialized methods, both an ordering (parser-sort),
> and simplify method, and call them alternately until no further changes
> are made.  (You might be able to combine them in the sort process as an
> optimization.)
>
> A constrained sort would be a combination of splitting (parsing) the
> list into sortable sub lists and sorting each sub list, possibly in a
> different manner, then reassembling it back.  And doing that possibly
> recursively till no further improvements are made or can be made.

I think a comparison function which is passed into Pythons builtin
sort() should be sufficient to solve the problem. I guess the
comparison defines a total order on the set of elements defined by the
list to sort.

> On a more general note, I think a constrained sort algorithm is a good
> idea and may have more general uses as well.
>
> Something I was thinking of is a sort where instead of giving a
> function, you give it a sort key list.  Then you can possibly sort
> anything in any arbitrary order depending on the key list.
>
> sort(alist, [0,1,2,3,4,5,6,7,8,9])   # Sort numbers forward
> sort(alist, [9,8,7,6,5,4,3,2,1,0])   # Reverse sort
> sort(alist, [1,3,5,7,9,0,2,4,6,8])   # Odd-Even sort
> sort(alist, [int,str,float]) # sort types

Seems like you want to establish a total order of elements statically.
Don't believe that this is necessary.

> These are just suggestions, I haven't worked out the details.  It could
> probably be done currently with pythons built in sort by writing a
> custom compare function that takes a key list.

Exactly.

> How fine grained the key
> list is is also something that would need to be worked out.  Could it
> handle words and whole numbers instead of letters and digits?  How does
> one specify which?  What about complex objects?

In order to handle complex objects one needs more algebra ;)

Since the class M only provides one operation I made the problem as
simple as possible ( complex expressions do not exist in M because
__mul__ is associative  - this is already a reduction rule ).

Kay

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


Re: Ordering Products

2005-07-18 Thread Kay Schluehr
Bernhard Holzmayer schrieb:
> Kay Schluehr wrote:
>
> >
> > Now lets drop the assumption that a and b commute. More general: let be
> > M a set of expressions and X a subset of M where each element of X
> > commutes with each element of M: how can a product with factors in M be
> > evaluated/simplified under the condition of additional information X?
> >
> > It would be interesting to examine some sorting algorithms on factor
> > lists with constrained item transpositions. Any suggestions?
> >
>
> Hello Kay,
>
> take this into account:
> Restrictions like commutativity, associative, distributive and flexibility
> laws don't belong neither to operands nor to operators themselves.
> Instead these are properties of fields (set of numbers with respect to a
> certain operation).
> For a famous example for a somewhat "alternative" behaviour look at the
> Octonions (discovered in 1843 by Graves and 1845 by Cayley), which are not
> associative with respect to addition and/or multiplication.
> (http://en.wikipedia.org/wiki/Octonions) or the Quarternions, which are
> non-commutative (http://en.wikipedia.org/wiki/Quaternion)
>
> Obviously, it's not correct to say: addition is associative, or, that
> multiplication is. With the same right, you could say, multiplication is
> not associative.

It was associative in the tiny example I presented. I did not mentioned
to discuss the evolving structure of the whole CAS here in detail which
would be better done in an own newsgroup once an early version is
released.

Maybe the setting of the original question should be made more precise:
associative, non-commutative multiplicative groups.

Handling non-associative algebras like Lie algebras is a completely
different matter and I'm not even sure which one is the best way to
represent operations in Python?

Maye this way?

>>> lie = Lie()   # create an arbitrary Lie algebra (lie is again a class )
>>> A,B = lie(),lie() # create two arbitrary elements of the Lie algebra
>>> lie[A,B]  # create the commutator of the lie algebra by overloading
lie[A,B]  # the __getitem__ method

>>> lie[A,B] == -lie[-A,B]
True

If one wants to enforce assertions like

>>> lie[r*A,B] == r*lie[A,B]
True

for certain elements r of some group acting on lie, one must refine
creation of lie in the initial assignment statement e.g.

>>> lie = Lie(V)

where V is some vectorspace and the elements of lie are homomorphisms
on V. V is created elsewhere. There are a lot of constraints induced by
all the objects dynamically coupled together.

> With the same reasoning, we can show that it's not easy to generalize
> sorting, commutation, association or distribution mechanisms.
>
> Maybe it would be a very fascinating goal to solve your algorithmic approach
> in such a limited environment like the Quarternions.

No CAS can represent infinitely many different representations of
quaternions. But it should not be to hard to deal with an algebra that
represents admissable operations on quaternions in an abstract fashion.

> A solution for this set of numbers, if achieved in a clean, mathematically
> abstract way, should hold for most other numbers/fields too, natural and
> real included.
>
> I guess that the approach might be this way:
> - define/describe the fields which shall be handled
> - define/describe the rules which shall be supported
> - find methods to reduce sequences of operations to simple binary or unary
> operations (tokens) - this may introduce brackets and stacking mechanisms
> - a weighing algorithm might be necessary to distinguish between plain
> numbers and place holders (variables)
> - application of the distributivity (as far as possible) might help to find
> a rather flat representation and a base for reordering according to the
> weights of the individual sub-expressions
>
> Nevertheless, there are lots of commercial programs which do such sort of
> symbolic mathematics, and which would badly fail when it would come to such
> awkward fields like Quarternions/Octonions.

If you take a look on Mathematica or Maple both programs seem to
interpret pure symbols as members of an associative and commutative
algebra:

   expand( (a+x)^2)  -> a^2 + 2ax + x^2

This works very fast and accurate but is mathematically too restricted
for me. For doing more advanced stuff one needs to do a lot of
programming in either language shipped with the CAS for creating new
packages. But then I ask myself: why not doing the programming labor in
Python and redesign and optimize the core modules of the CAS if
necessary? 

Kay

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


Re: goto

2005-07-18 Thread Kay Schluehr

Hayri ERDENER schrieb:
> hi,
> what is the equivalent of C languages' goto  statement in python?
> best regards

No, but some of goto's use cases can be covered by unconditional jumps
provided by exceptions.


Here is a C function using goto:

void main()
{
int i, j;

for ( i = 0; i < 10; i++ )
{
printf( "Outer loop executing. i = %d\n", i );
for ( j = 0; j < 2; j++ )
{
printf( " Inner loop executing. j = %d\n", j );
if ( i == 3 )
goto stop;
}
}
/* This message does not print: */
printf( "Loop exited. i = %d\n", i );
stop: printf( "Jumped to stop. i = %d\n", i );
}


And here is a Python equivalent using exception handling:

def main():
class stop(Exception):pass
try:
for i in range(10):
print "Outer loop executing. i = %d"%i
for j in range(2):
print " Inner loop executing. j = %d"%j
if i == 3:
raise stop
print "Loop exited. i = %d"%i  # message does not print
except stop:
print "Jumped to stop. i = %d"%i 


Regards,
Kay

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


Re: Ordering Products

2005-07-18 Thread Kay Schluehr
Ron Adam wrote:
> Kay Schluehr wrote:
> > Here might be an interesting puzzle for people who like sorting
> > algorithms ( and no I'm not a student anymore and the problem is not a
> > students 'homework' but a particular question associated with a
> > computer algebra system in Python I'm currently developing in my
> > sparetime ).
> >
> > For motivation lets define some expression class first:
>
>
> This works for (simple) expressions with mixed multiplication and addition.
>
>
> class F(list):
>  def __init__(self,*x):
>  #print '\nF:',x
>  list.__init__(self,x)
>  def __add__(self, other):
>  return A(self,other)
>  def __radd__(self, other):
>  return A(other,self)
>  def __mul__(self, other):
>  return M(self,other)
>  def __rmul__(self, other):
>  return M(other,self)
>  def __repr__(self):
>  return str(self[0])
>  def __order__(self):
>  for i in self:
>  if isinstance(i,A) \
>  or isinstance(i,M):
>  i.__order__()
>  self.sort()
>
> class A(F):
>  def __init__(self, *x):
>  #print '\nA:',x
>  list.__init__(self, x)
>  def __repr__(self):
>  self.__order__()
>  return "+".join([str(x) for x in self])
>
> class M(F):
>  def __init__(self,*x):
>  #print '\nM:',x
>  list.__init__(self,x)
>  def __repr__(self):
>  self.__order__()
>  return "*".join([str(x) for x in self])
>
>
> a = F('a')
> b = F('b')
> c = F('c')
> d = F('d')
>
> print '\n a =', a
>
> print '\n b+a+2 =', b+a+2
>
> print '\n c*b+d*a+2 =', c*b+d*a+2
>
> print '\n 7*a*8*9+b =', 7*a*8*9+b
>
>
>
>  >>>
>
>   a = a
>
>   b+a+2 = 2+a+b
>
>   c*b+d*a+2 = 2+a*d+b*c
>
>   7*a*8*9+b = 9*8*7*a+b  <--  reverse sorted digits?
>  >>>
>
>
> The digits sort in reverse for some strange reason I haven't figured out
> yet, but they are grouped together.  And expressions of the type a*(c+b)
> don't work in this example.
>
> It probably needs some better logic to merge adjacent like groups.  I
> think the reverse sorting my be a side effect of the nesting that takes
> place when the expressions are built.
>
> Having the digits first might be an advantage as you can use a for loop
> to add or multiply them until you get to a not digit.
>
> Anyway, interesting stuff. ;-)
>
> Cheers,
> Ron

Hi Ron,

I really don't want to discourage you in doing your own CAS but the
stuff I'm working on is already a bit more advanced than my
mono-operational multiplicative algebra ;)

Mixing operators is not really a problem, but one has to make initial
decisions ( e.g about associativity i.e. flattening the parse-tree )
and sub-algebra generation by means of inheritance:

>>> a,b = seq(2,Expr)
>>> type(a+b)


>>> class X(Expr):pass
>>> x,y = seq(2,X)
>>> type(x+y)


This is not particular hard. It is harder to determine correspondence
rules between operations on different levels. On subalgebras the
operations of the parent algebra are induced. But what happens if one
mixes objects of different algebras that interoperate with each other?
It would be wise to find a unified approach to make distinctive
operations visually distinctive too. Infix operators may be
re-introduced just for convenience ( e.g. if we can assume that all
algebras supporting __mul__ that are relevant in some computation have
certain properties e.g. being associative ).


##

After thinking about M ( or Expr ;) a little more I come up with a
solution of the problem of central elements of an algebra ( at least
the identity element e is always central ) that commute with all other
elements.

Here is my approach:

# Define a subclass of list, that provides the same interface as list
and
# a customized sorting algorithm

import sets

class Factors(list):
def __init__(self,li):
list.__init__(self,li)
self.elems   = sets.Set(li)   # raw set of factors used in the
__mul__
self._center = () # storing central elements
commuting with
  # with all others

def _get_center(self):
return self._center

def _set_center(self,center):
Center = sets.Set(center)
if not Center<=self.elems:
raise ValueError,"Subset required"
else:
 

Re: Ordering Products

2005-07-19 Thread Kay Schluehr
Diez B.Roggisch wrote:
> > I have to admit that I don't understand what you mean with the
> > 'constant parts' of an expression?
>
> >From what I percieved of your example it seemed to me that you wanted to
> evaluate the constants like 7*9 first, so that an expression like
>
> a * 7 * 9 * b
>
> with variables a,b is evaluated like this:
>
> a * 63 * b
>
> So my suggestion was simply to make the *-operator more precedent when
> in between two constants. What I mean with constants here are  of course
> integer/float literals. The concept of a differing operator precedence
> can be extended to arbitray elements when their types are known - which
> should be possible when variable values are known at parsing
> time.

O.K.

>
> > The associativity of __mul__ is trivially fullfilled for the dummy
> > class M if an additional __eq__ method is defined by comparing factor
> > lists because those lists are always flat:
>
> I don't care about that, as my approach deosn't use python's built-in parser
>  - it can't, as that wouldn't allow to re-define operator  precedence.

Diez, I try not to care too much about global operator precedence of
builtin infix operators. The hard problems in designing a CAS beyond
Mathematica are related to a bunch of interoperating algebras all
defining their own operations. Finally only local precedences exist
that are characteristic for certain patterns of expressions with a lot
of tangled operators ( e.g. 'geometric algebra' with vector products,
wedge products, inner products, additions and subtractions ). I don't
want a system defining a syntactically extendable language with 10
custom punctuations per module that no one ( at least not me ) can
remind and which looks as awkward as regular expressions.


> What you do is to
> simply collect the factors as list. But what you need (IMHO) is a parsing
> tree (AST) that reflects your desired behaviour by introducing a different
> precedence thus that the expression
>
> a * 7 *9 * b
>
> is not evaluated like
>
> ((a*7)*9)*b
>
> (which is a tree, and the standard way of evaluationg due to built-in parsers
> precedence rules) but as
>
> a*(7*9)*b
>
> which is also a tree.

Yes, but I tend to use __mul__ just for convenience. It is reflecting
an associative and non-commutative operator whereas __add__ is a
convenient way to fix an associative and commutative operator. In an
idealized mathematical interpretation they represent nothing specific
but as language elements they shall be fixed somehow.

For more general operations one may define functional operators e.g.
r_assoc and l_assoc where following (in)equations hold:

l_assoc(a,b,c) == l_assoc(l_assoc(a,b),c)
l_assoc(a,b,c) != l_assoc(a, l_assoc(b,c))

r_assoc(a,b,c) == r_assoc(a,r_assoc(b,c))
r_assoc(a,b,c) != r_assoc(r_assoc(a,b),c)

This kind of pattern can be used to define rules about l_assoc and
r_assoc.

Nevertheless, there is no loss of generality. The system lacks
prevention from deriving some class providing __mul__ and overwrite the
implementation of __mul__ using l_assoc. People may do this on their
own risk. 

Kay

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


Documentation bug: Python console behaviour changed

2005-07-19 Thread Kay Schluehr
The documentation of the Python console behaviour is not correct
anymore for Python 2.4.1. At least for the Win2K system I'm working on
'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc.

The Python interpreter tells me instead:

>>> quit
'Use Ctrl-Z plus Return to exit.'

Nah, 'Ctrl-Z' is now undo :-)

Side remark: IDLE closes the console either with Ctrl-D or Ctrl-Q. But
IDLEs configure dialog window showing the key combinations is so tight
and nothing is recognizable without scrolling back and forth that it is
discouring to use it at all ;)

IPython closes with 'Ctrl-D'. Thanks to IPython I also determined this
as the correct shutdown keys for Python too.

Kay

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


Re: Documentation bug: Python console behaviour changed

2005-07-19 Thread Kay Schluehr


Peter Hansen schrieb:
> Kay Schluehr wrote:
> > The documentation of the Python console behaviour is not correct
> > anymore for Python 2.4.1. At least for the Win2K system I'm working on
> > 'Ctrl-Z' does not shut down the console but 'Ctrl-D' etc.
> >
> > The Python interpreter tells me instead:
> >
> >
> >>>>quit
> >
> > 'Use Ctrl-Z plus Return to exit.'
> >
> > Nah, 'Ctrl-Z' is now undo :-)
>
> Are you really using the console, started with the "Command Prompt" icon
> from the Start Menu (or some equivalent)?
> And are you sure you haven't
> installed something else that magically changed the behaviour of Ctrl-Z?
>
> (I get the documented behaviour with Python 2.4.1, under Win XP.)
>
> -Peter

Well, Peter, I indeed changed the system magically but yet it was not
Windows, but Python! In my description I told You that I installed
IPython and IPython requires the readline package. If I rename the
readline package ( e.g. _readline ) in the site-packages directory the
console behaves as expected. Otherwise it shows the termination
behaviour of IPython namely it shuts down with Ctrl-D.

It's really sucking...

Kay

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


Re: Ordering Products

2005-07-19 Thread Kay Schluehr
Ron Adam wrote:
> Kay Schluehr wrote:
>
>
> > Hi Ron,
> >
> > I really don't want to discourage you in doing your own CAS but the
> > stuff I'm working on is already a bit more advanced than my
> > mono-operational multiplicative algebra ;)
>
> I figured it was, but you offered a puzzle:
>
>"Here might be an interesting puzzle for people who like sorting
> algorithms ..."
>
> And asked for suggestions:
>
>"It would be interesting to examine some sorting algorithms on factor
> lists with constrained item transpositions. Any suggestions?"
>
> So I took you up on it.   ;-)
>
>
> BTW.. Usually when people say "I don't want to discourage...", They
> really want or mean the exact oppisite.

Yes, but taken some renitence into account they will provoke the
opposite. Old game theoretic wisdoms ;)

> This is a organizational problem in my opinion, so the challenge is to
> organize the expressions in a way that can be easily manipulated
> further.  Groupings by operation is one way.  As far as inheritance
> goes, it's just another way to organize things.  And different algebra's
> and sub-algebra's are just possible properties of a group. The groups
> can easily be customized to have their own behaviors or be created to
> represent custom unique operations.
>
> The sort method I'm suggesting here, with examples, is constrained by
> the associated properties of the group that is being sorted.  Basically,
> weather or not it's and associative operation or not.  So when a group
> is asked to sort, it first asks all it's sub groups to sort, then it
> sorts it self if it is an associative group.  Ie.. from inner most group
> to outer most group but only the associative ones.

But you seem to fix behaviour together with an operation i.e. declaring
that __mul__ is commutative. But in a general case you might have
elements that commute, others that anti-commute ( i.e. a*b = -b*a ) and
again others where no special rule is provided i.e. they simply don't
commute.

But much worse than this the definition of the operations __add__,
__mul__ etc. use names of subclasses A,D explicitely(!) what means that
the framework can't be extended by inheritance of A,D,M etc. This is
not only bad OO style but customizing operations ( i.e. making __mul__
right associative ) for certain classes is prevented this way. One
really has to assume a global behaviour fixed once as a class
attribute.

>
> Playing with it further I get the following outputs.
>
> ( The parenthesis surround a group that is associated to the operation.
>   This is the same idea/suggestion I first proposed, it's just been
> developed a little further along.)
>
>
>   b+a+2 = (2+a+b)<- addition group
>
>   a*(b+45+23) =  ((68+b)*a)  <- addition group within multiply group
>
>   a-4-3-7+b =  ((a-14)+b)<- sub group within add group
>
>   c*b-d*a+2 = (2+((b*c)-(a*d)))  <- mults within subs within adds
>
>   7*a*8*9+b = ((504*a)+b)
>
>   a*(b+c) = ((b+c)*a)
>
>   c*3*a*d*c*b*7*c*d*a = (21*a*a*b*c*c*c*d*d)

I still don't see how you distinguish between factors that might
commute and others that don't. I don't want a and b commute but c and d
with all other elements.


>   d*b/c*a = (((b*d)/c)*a)
>
>   (d*b)/(c*a) = ((b*d)/(a*c))
>
>   d*b-a/e+d+c = (((b*d)-(a/e))+c+d)
>
>   a/24/2/b = (a/48/b)
>
>   c**b**(4-5) = (c**(b**-1))
>
>   (d**a)**(2*b) = ((d**a)**(2*b))

If you have fun with those identities you might like to find
simplifications for those expressions too:

a*0   -> 0
a*1   -> a
1/a/b -> b/a
a+b+a -> 2*a+b
a/a   -> 1
a**1  -> a

etc.

> The next step is to be able to convert groups to other groups; an
> exponent group to a multiply group; a subtract group to an addition
> group with negative prefix's.. and so on.
>
> That would be how expansion and simplifying is done as well as testing
> equivalence of equations.
>
> if m*c**2 == m*c*c:
>print "Eureka!"
>
>
> > Mixing operators is not really a problem, but one has to make initial
> > decisions ( e.g about associativity i.e. flattening the parse-tree )
> > and sub-algebra generation by means of inheritance:
>
> What do you mean by 'sub-algebra generation'?

Partially what I described in the subsequent example: the target of the
addition of two elements x,y of X is again in X. This is not obvious if
one takes an arbitrary nonempty subset X of Expr.

> >>>>a,b = seq(2,Expr)
> >>>>type(a+b)
> >
> > 
> >
> >>>>class X(Expr):pass
> >>>>x,y = seq(2,X)
>

Re: python certification

2005-07-20 Thread Kay Schluehr


[EMAIL PROTECTED] schrieb:
> hi
> i bassically need it cuz i am appyling to colleges this year and
> i know this kind of stuff really helps.
> besides since i am learning python i thought i might get some credit
> for it as well.
> its bassically for a mention in my resume/bio-data/appliccation
> i am willing to spend about $50-100 but any more is out of my bugdet.
> even $50 is hard on me.
> i did find this great site that would  let me give a perl exam in $9.99
> but they don't have python.

Before you spend some of your few money for an obscure certification
without any authority you should feel certain that you need Python at
your college. Better you participate in an open source project for fun
and gathering some experience if it's not too hard for you to access a
computer. Of course I don't know your supervisors and I'm not sure
whether they are more impressed about people learning the Python
tutorial, than about people using it to write real world applications.

Kay

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


Re: python certification

2005-07-20 Thread Kay Schluehr
Andreas Kostyrka schrieb:

> (These are the people look for Pearl and Pyhton programmers ;) )

Or Phyton :)

Kay

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


Re: Lists & "pointers"

2005-07-23 Thread Kay Schluehr
Jan Danielsson wrote:
> Hello all,
>
>I have written a simple whiteboard application. In my application, I
> want to be able to set draw attributes. This part works. I have a
> dictionary object which contains stuff like:
> self.attr['Pen.Color'] = ...
> self.attr['Pen.Thickness'] = ...
>
>Now, the problem is that I want to be able to store attributes in a
> list so they'll be easily accessed using the function keys. I.e. I have
> the "current attributes" which I want to be able to store or retrieve
> in/from a list,
>
> The problem is that I have initialized the list like this:
>
> self.drawAttr = { blah, blah, blah.. }
> self.storedAttr = [ ]
> for i in range(0, 10):
>self.storedAttr.append(self.drawAttr)
>
>I know what the problem is; they are all referencing the *same*
> dictionary object. So, my question is: How do I initialize a list of
> dictionary objects, where each list entry is its own object (which is a
> copy from the self.drawAttr object).

Hi Jan son of Daniel,

you might initialize self.storedAttr with empty dicts and fill them
later:

self.soredAttr = [{}]*10
for entry in self.storedAttr:
entry.update(self.drawAttr)


> Also, how do I store/restore entries to the list?
>
>I have found the "copy" module, and it's copy method. I assume this
> would work:
>
> for i in range(0, 10):
>self.storedAttr.append(copy.copy(self.drawAttr))
>
>However, the concept of "deep copy" confuses me. Do I want it, or
> don't I want it? I repeat: the attributes object is a simple dictionary.
>
> Thankful for any advice.

A *shallow copy* creates a new dictionary and copies the references, a
*deep copy* tries to create a new reference for each existing object in
the dict. The disadvantage of deepcopy is that it does not work in many
cases:

>>> copy.deepcopy([lambda :None])
Traceback (most recent call last):
...
TypeError: function() takes at least 2 arguments (0 given)

As the docs tell:

"This version does not copy types like module, class, function, method,
stack trace, stack frame, file, socket, window, array, or any similar
types."

I wonder if one couldn't pickle a module and reimport it in order to
create a copy of it ;)

IMO this is a weakness of the algorithm. One usually doesn't want to
duplicate a function so that a new reference of a function is not
needed because it is readonly and the algorithm could reuse the same
reference. For classes I don't if the assertion in the docs is actually
true?

>>> class A:pass
>>> copy.deepcopy(A)


>>> class A(object):
... def __init__(self):pass
... 
>>> copy.deepcopy(A)

>>> 

Regards,
Kay

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


Re: A replacement for lambda

2005-07-30 Thread Kay Schluehr

Tim Roberts schrieb:

> Scott David Daniels <[EMAIL PROTECTED]> wrote:
> >
> >What kind of shenanigans must a parser go through to translate:
> > <
> >
> >this is the comparison of two functions, but it looks like a left-
> >shift on a function until the second with is encountered.  Then
> >you need to backtrack to the shift and convert it to a pair of
> >less-thans before you can successfully translate it.
>
> C++ solves this exact problem quite reasonably by having a greedy
> tokenizer.  Thus, that would always be a left shift operator.  To make it
> less than and a function, insert a space:
> < 
> --
> - Tim Roberts, [EMAIL PROTECTED]
>   Providenza & Boekelheide, Inc.

Python does have such a greedy/longest match tokenizer too:

>>> 2 .__add__(3)   # insert whitespace before dot
5

>>> 2.__add__(3)# 2. is a float
-> Exception

Kay

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


Re: A replacement for lambda

2005-07-30 Thread Kay Schluehr
Mike Meyer schrieb:

> I know, lambda bashing (and defending) in the group is one of the most
> popular ways to avoid writing code. However, while staring at some Oz
> code, I noticed a feature that would seem to make both groups happy -
> if we can figure out how to avoid the ugly syntax.
>
> This proposal does away with the well-known/obscure "lambda"
> keyword. It gives those who want a more functional lambda what they
> want. It doesn't add any new keywords. It doesn't add any new magic
> characters, though it does add meaning to an existing one. That could
> be replaced by a new magic token, or adding magic meaning to a
> non-magic token. It breaks no old code either way.

Mike,

in modern functional language design one starts with certain lambda
expressions and add syntax sugar ( operational / statement syntax ) for
constructs based on them. In Python statement- and expression syntax
were introduced seperately. Pythons lambda is simply the symptom of
this separation. Now you suggest ( not the first time on this list or
at python-dev ) to put statements into expressions leading to a strange
syntax and conflicting with Pythons indentation rules.

Another way to deal with the restrictions of lambda is going the other
way round and simply propose expression syntax for conds and
assignments.

Using guards '||' and the keyword 'then' for conditional expressions:

   ( || x>=0 then f(x) || True then f(-x) )

Or shorter dropping 'then' in the second condition:

( || x>=0 then f(x) || f(-x) )

Both translates to:

  if x>=0:
 f(x)
  else:
 f(-x)

Using a reverse arrow for assignments:

 x <- y

For loops can be replaced by functional constructs ( use map() or a
list/generator comprehension ).

Finally the lambda keyword can be replaced by expressional syntax e.g.
( EXPR from ARGS ):

Examples:
   f = ( || x>=0 then f(x) || True then f(-x)  from (x,) )
   g = ( || x< 0 then self._a <-x || self._a <- 0 from (x,))

Kay

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


Re: A replacement for lambda

2005-07-30 Thread Kay Schluehr
Paul Rubin wrote:
> "Kay Schluehr" <[EMAIL PROTECTED]> writes:
> > Examples:
> >f = ( || x>=0 then f(x) || True then f(-x)  from (x,) )
> >g = ( || x< 0 then self._a <-x || self._a <- 0 from (x,))
>
> Is this an actual language?  It looks sort of like CSP.  Python
> with native parallelism, m.

The syntax was inspired by OCamls pattern matching syntax:

match object with
  pattern1->  result1
| pattern2->  result2
| pattern3->  result3
...

But for Python we have to look for an expression not a statement
syntax. In order to prevent ambiguities I used a double bar '||'
instead of a single one. 

Kay

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


Re: Ten Essential Development Practices

2005-07-30 Thread Kay Schluehr
Dark Cowherd wrote:

> -Quote - Phillip J. Eby from dirtsimple.org
> Python as a community is plagued by massive amounts of
> wheel-reinvention. The infamous web framework proliferation problem is
> just the most egregious example.
>
> Why is Python "blessed" with so much reinvention? Because it's often
> cheaper to rewrite than to reuse. Python code is easy to write, but
> hard to depend on. You pretty much have to:
>
>1. limit yourself to platforms with a suitable packaging system,
>2. bundle all your dependencies into your distribution, or
>3. make your users do all the work themselves
>
> Ouch. No wonder rewriting looks easier. The only way to stop this
> trend is to make it easier to reuse than to rewrite, which has been my
> mission with setuptools and EasyInstall
> -UnQuote

I think that Phillip misrepresents the problem a little bit, because it
is not true that there are too few reusable components that need just
another hero programmer like himself or anyone of us to implement. What
is missing is just a simple distinction that does not exist in an open
source community guided by hackers at least not on a certain level (
the PEP process would be a counter-example ) but is well known in
contemporary industry practice: some people are just writing specs. SUN
with Java for example employs people that model systems and write API
specs that are finally licenced and implemented by 3rd-party vendors.
J2EE or the JavaCard API are prominent examples. This is very different
from the just-for-fun or heroic-hacker attitude due to spare-time
programmers who create a bit of code they are interested in and leaving
the rest aside. It's not all just marketing blabla that makes Javas
success. 



Kay

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


Re: Comparison of functions

2005-07-30 Thread Kay Schluehr
Some indications:

>>> for i in range(5):
... x = lambda x:x
... y = lambda y:y
... print x,y,x at 0x00EE83F0>  at 0x00EE8FB0>
True True
 at 0x00EE8AB0>  at 0x00EE83F0>
False False
 at 0x00EE8FB0>  at 0x00EE8AB0>
False False
 at 0x00EE83F0>  at 0x00EE8FB0>
True True
 at 0x00EE8AB0>  at 0x00EE83F0>
False False

Regards,
Kay

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


Re: Wheel-reinvention with Python

2005-07-31 Thread Kay Schluehr

Ed Leafe wrote:
> On Sunday 31 July 2005 01:02, phil hunt wrote:
>
> > You mightn't have, but I suspect more Python programers who've
> > written GUI apps have used Tkinter than any of the other APIs.
> >
> > Not that I'm a particular fan of it, it's just I like
> > standardisation, because then you get network effects.
>
>  At PyCon DC 2004, Guido was asked about wxPython: "wxPython is the best and
> most mature cross-platform GUI toolkit, given a number of constraints. The
> only reason wxPython isn't the standard Python GUI toolkit is that Tkinter
> was there first."

Maybe. But Guidos intention with Python was to create a secondary
language originally - an extension language of C - ( unlike Java that
was concepted as a radically platform independent language and a
successor of C++ ).  Now since Python is 15 years old, some people
start learning Python as their primary language and they begin to ask
why it does not support a native GUI toolkit like TCL with Tk i.e.
something in it's own right with just some C-modules for interfacing
with OS dependent libs ( if any - thanks to the ctypes ffi ! ) and some
other extensions for optimization and maybe scintilla for pluging it
in.

Some other people already abandoned Python not for the worst reasons:

http://www.kevin-walzer.com/pivot/entry.php?id=69

My objection with wrappers around wrappers around wrappers is that I
have no hope ever watching the ground. If some error occurs, which
layer has to be addressed? Which developing group is reponsible? My own
or that of team A, team B, team C ... ? The baroque concept is
repulsive to me and only acceptable in case of legacy code that gets
wrapped around old one and is dedicated to substitute it continously.

Kay

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


Re: Wheel-reinvention with Python

2005-07-31 Thread Kay Schluehr
Cliff Wells wrote:

> > My objection with wrappers around wrappers around wrappers is that I
> > have no hope ever watching the ground. If some error occurs, which
> > layer has to be addressed? Which developing group is reponsible? My own
> > or that of team A, team B, team C ... ? The baroque concept is
> > repulsive to me and only acceptable in case of legacy code that gets
> > wrapped around old one and is dedicated to substitute it continously.
>
> Of course, Tkinter is still a wrapper around a third party library (Tk)
> borrowed from a different language (Tcl) and written again in a third
> language (C), much the same as wxPython.

Yes, sorrowly. But the discussion was focussed around another layer
above wxPython, Tkinter etc. to make those toolkits more pythonic. Ed
promised to support many GUI toolkits as backend in future ( reviving
the failed AnyGUI approach ). That's o.k. as long as tedious
maintenance is a fun job for some people and they do it right. I don't
say that Ed produces crap, but I'll be carefull and wait a couple of
years before using such kind of stuff in production code.

> Your concerns are valid in a theoretical sense, but in practice make
> little difference.

It makes all difference in practice. A few levels of stacking does not
hurt in theory because it is easy to abstract them away by perfect
machinery.

> If you are using Tkinter and it exposes a bug in Tk,
> then you report to the Tkinter maintainers and they will get it fixed.

As long as the chain of layers does not break and the conveyor-belt
rolls efficiently it's like living in theory ;)

Kay

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


Re: namespaces

2005-07-31 Thread Kay Schluehr
Paolino wrote:

> The second point also shows my perplexities about functions namespace:
>
> def function():
>function.foo='something'
>
> a=function.foo
>
> Traceback (most recent call last):
>File "", line 1, in ?
> AttributeError: 'function' object has no attribute 'foo'
>
> How should I read it? The namespace is half done inside the function?

Don't know what you mean with "half done"?

In order to understand Python you have to care about it's dynamic
nature. The "def function()" is an executable definition that produces
a function object that gets bound to a new global name "function".
After "function" is created it may be manipulated inside it's own body
much like it is possible to call it recursively. That's why this should
work:

def function():
function.foo='something'

>>> function()
>>> a=function.foo

By the way. Did you understand the hint Paul Rubin tried to offer?
Defining an __all__ = [...] variable in your module makes exactly those
names visible to other modules that are contained in the list. You
might pollute your modules namespace but this is exactly what is it
good for. You just have to care not to pollute the namespaces of other
modules preserving locality.

Kay

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


Re: Wheel-reinvention with Python

2005-08-01 Thread Kay Schluehr
Reinhold Birkenfeld wrote:

> > In practise any Python GUI is going to contain code from otyher
> > languages since if it was coded all the way down in python it would
> > be too slow.
>
> Oh, I could imagine that a MFC-like wrapper around win32gui, or another
> one around Xlib wouldn't be slower that wxWidgets is today.
>
> Reinhold

Hi Reinhold,

did You have a look at 'venster'?

http://venster.sourceforge.net/htdocs/index.html

They even dropped win32gui and worked with ctypes and the Win32API
reducing the C-footprint. For frameworks like Dabo, AnyGUI, PyGUI etc.
this would be the right level to create an abstraction layer IMO. By
the way the demo applications of venster run stable and fast on WinXP.

Kay

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


Decline and fall of scripting languages ?

2005-08-06 Thread Kay Schluehr
No good news for scripting-language fans:

http://www.phpmag.net/itr/news/psecom,id,23284,nodeid,113.html

Regards
Kay

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


[email protected]

2005-08-06 Thread Kay Schluehr
[EMAIL PROTECTED] wrote:
> I've heard 2 people complain that word 'global' is confusing.
>
> Perhaps 'modulescope' or 'module' would be better?
>
> Am I the first peope to have thought of this and suggested it?
>
> Is this a candidate for Python 3000 yet?
>
> Chris

Maybe a solution would be best that is able to resolve shadowing of a
variable in an explicit manner.

Example. you might have the following nested function:

x = 0
def h():
x = 1 # module scoped x will be shadowed
def g():
x = 2 # module scoped x and h's local x will be
shadowed
def f():
print x   # printing x defined locally in g
f()
g()

The module level x is always accessible from each inner function using
the global keyword but it is not possible to access x defined locally
in h from f.

Two hypothetical variants using an "unshadow operator" & explicitely:

x = 0
def h():
x = 1
def g():
x = 2
def f():
print &x # unshadowing x defined in h
f()
g()


x = 0
def h():
x = 1
def g():
x = 2
def f():
print &&x # unshadowing x defined on module level
f()
g()

Since we can always shadow some module scoped variable defining a local
one we might create a side-effect binding values to the unshadowed
name:

x = 0
def f():
x = 1
&x = 7

>>> f()
>>> x
7

Regards,
Kay

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


Re: Fat and happy Pythonistas (was Re: Replacement for keyword 'global' good idea? ...)

2005-08-06 Thread Kay Schluehr
John Roth wrote:

> Another thing that stands out: the explicit versus dynamic typing debate
> has moved on from program correctness (which is a wash) to
> other areas that explicit (or derived) type information can be used
> for. I see this in PyFit: the languages where explicit type information
> is available by reflection have cleaner implementations.

What makes myself a fat and lazy Pythonista is simply motivated by not
wanting Guido throwing any language feature that someone found
accidentally in another language into Python. My personal attitude is
that I have enough self-confidence that I can live with just the second
most popular programming language in the world. And maybe I'm also fat
because I like to feed myself ( my topics of interest ) and not people
with consumerist attitudes.

So you have recognized that dynamic languages don't support type
reflections well. Surprise, surpise! Other wellinformed authors like
Benjamin Pierce wouldn't even agree about Python as being typed but
dynamically *tagged*. Now what do you recommend? Sacrificing
__delattr__, __setattr__, decorators and metaclasses for having
colorcoding editors and a Java-like language with indentation syntax?
What do you believe to ensure with type-declarations extracted by tools
in presence of magic methods that enable to rewrite your class on the
fly? Of course some things become harder in Python because they are
impossible to guarantee in general. The PyPy team spends a lot of
effort in exploring the boundary between what can be inferred from
Python code and translated into lower level languages before program
execution and what has to be passed to some code specializer at
runtime. That's where new insights about dynamic languages may come
from.

Kay

PS. I don't have anything against Ruby. May it have many cheerleaders!
It's just that Haskell is on top of my list of interesting PLs I didn't
devote much time yet and Ruby is far away.

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


Re: Decline and fall of scripting languages ?

2005-08-06 Thread Kay Schluehr
Paul Rubin wrote:
> Cliff Wells <[EMAIL PROTECTED]> writes:
> > It didn't say what they left PHP, Perl and Python for (if you are to
> > even believe their findings).
> >
> > PHP has been losing programmers in droves... to Ruby on Rails, but I'm
> > not sure how that is bad news for scripting-language fans.
>
> That's the second time in one or two days that I've heard Ruby on
> Rails mentioned.  Can anyone here post a paragraph or two description?
> I sort of know what Ruby is, a very OOP-ified Perl-resemblant
> language, that's also implemented only as an interpreter.  I can't see
> punting Python for it.

Exacly. While Pythons main attitude is reducing clutter and redundant
design while staying within an OO mindframe, Ruby reintroduces perlish
clutter. Ruby was mentioned to be a more clean OO language than Python
in times where Python didn't support inheritance from builtins.
Nowadays anonymus blocks are the single most discriminative feature
Ruby is praised for. Therefore Ruby seems to be more modern than Python
to some people allthough it's design concept is reactionary - or
"postmodern" what may be the same in post-postmodern times ;-)

> Lately I'm interested in OCAML as a possible step up from Python.  It
> has bogosity of its own (much of it syntactic) but it has static
> typing and a serious compiler, from what I understand.  I don't think
> I can grok it from just reading the online tutorial; I'm going to have
> to code something in it, once I get a block of time available.  Any
> thoughts?

The whole ML family ( including OCaml ) and languages like Haskell
based on a Hindley-Milnor type system clearly make a difference. I
would say that those languages are also cutting edge in language theory
research. It should be definitely interesting to you. Since there is no
single language implementation you might also find one that supports
concepts you need most e.g. concurrency:

http://cml.cs.uchicago.edu/

Regards,
Kay

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


Re: Python -- (just) a successful experiment?

2005-08-07 Thread Kay Schluehr
Eric Pederson wrote:
> Raise your hand if you think the best technology wins!

Who is interested in such a matter? Is this a forum dedicated to some
programming language or a popularity contest?

If Python dies in a few years / looses attention but the Python Zen
survives in another language I have nothing to complain.

> For those of you with your hands in the air, tell me: if Python is so good,
> why has PHP achieved such greater adoption and mindshare?

PHP, Ruby and all this stuff is just the fashion of the day. If the
flow of money takes another direction away from Web programming I
believe there will still be C, some successor of Python, some members
of the ML/Haskell family rooted in CS, a deviation of C++/Java/C# and
some Lisp offspring and of course the new fashion of the day.

And in the end if the success of any language becomes dangerous somehow
it will be cloned and *improved* by Microsoft.

Kay

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


Re: Python -- (just) a successful experiment?

2005-08-07 Thread Kay Schluehr
Martin P. Hellwig wrote:
> Kay Schluehr wrote:
> > Eric Pederson wrote:
> >
> >>Raise your hand if you think the best technology wins!
> >
> >
> > Who is interested in such a matter? Is this a forum dedicated to some
> > programming language or a popularity contest?
> >
> > If Python dies in a few years / looses attention but the Python Zen
> > survives in another language I have nothing to complain.
> >
> 
> Ave!
> Although I think that the day that python is considerd dead is the same
> day that unix is truly dead.
> Ooh yes and I have heard for over two decades that unix-like systems are
> obsolete, so why is the install base only growing and has never been bigger?
>
> --
> mph

Of course "dead" has no absolute meaning for things that were never
alive.

May "infertile" be a better characterisation? If no new projects were
started using a certain language the language ( more precisely it's
runtime/libraries ) might become legacy and will be replaced
continously.

When the PyPy runtime becomes more mature and it's API somehow stable
we might see what is possible in the dynamic language area beyond the
current state of Python and also beyond Guidos projected Python3000. I
guess it will sprawl into several dialects pronouncing different
aspects: functional programming, concurrency, declarative programming a
mainline Python3000 and a legacy Python 2.X which remains to be
maintained.

Thinking about this prospects I don't actually believe that
Ruby-on-Rails will become a Python killer, just because it has a nice
installer.

Kay

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


Re: Chopping off spaces at both ends

2005-08-07 Thread Kay Schluehr
Use the strip() method.

Example:

>>> "\t abc\n".strip()
"abc"

Variants are lstrip() and rstrip().

Regards,
Kay

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


Re: PEP: Specialization Syntax

2005-08-07 Thread Kay Schluehr
Nicolas Fleury wrote:

> It is necessary to maintain a
> dictionary of types (to avoid redundacy) and simple things like:
>
> def makeType(someArgument):
>  class MyObject:
>  someArgument = someArgument
>  return MyObject
>
> are not allowed.

def makeClass(cls_name, **kw):
return type(cls_name,(), kw)

>>> MyObject = makeClass("MyObject",a=8)
>>> MyObject


>>> MyObject.a
8

Regards,
Kay

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


Re: PEP: Specialization Syntax

2005-08-08 Thread Kay Schluehr

Nicolas Fleury schrieb:

> Kay Schluehr wrote:
> > def makeClass(cls_name, **kw):
> > return type(cls_name,(), kw)
> >
> >>>>MyObject = makeClass("MyObject",a=8)
> >>>>MyObject
>
> As said to Bengt, a place is needed to write the class definition.
> There's no need for metaclass in that case:
>
> def makeType(a, b, c=someDefault):
>  arguments = locals()
>  class MyObject:
>  pass # Complete definition here
>  MyObject.__dict__.update(arguments)
>  return MyObject
>
> Regards,
> Nicolas

I have to admit that i don't actually understand what you want? The
problems you try to solve seem trivial to me but it's probably my fault
and i'm misreading something. You might be correct that your PEP may be
interesting only if "optional static typing" will be introduced to Py3K
and then we will suddenly have an immediate need for dealing with
generic types so that the syntax can be reused for deferred functions (
the concept of "specialization" is usually coupled with some kind of
partial evaluation which doesn't take place somewhere in your proposal
). But i'm not sure if this makes sense at all. 

Kay

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


Re: Python -- (just) a successful experiment?

2005-08-08 Thread Kay Schluehr
Paul Rubin schrieb:

> Having a good FFI is certainly an important feature but Python
> programs should first and foremost be Python programs.

Python was originally created as an extension language for C. In some
sense it is an abstraction layer for C libs.

> Compare the
> situation with Java or Common Lisp for example.  Both of those
> languages have better FFI's than Python in every serious
> implementation (consider why SWIG is popular--because Python's C API
> is so clumsy), and yet the specs for those languages are far more
> thorough than the Python docs.

Did you ever check out ctypes? I appreciate it very much.

http://starship.python.net/crew/theller/ctypes/

Kay

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


Re: Python -- (just) a successful experiment?

2005-08-08 Thread Kay Schluehr
Bengt Richter wrote:

> It occurs to me that we have the PEP process for core python, but no PEP 
> process
> for the python app/lib environment. What about starting a PEEP process
> (Python Environment Enhancement Proposals) modeled on PEPs, where those 
> motivated
> to formalize their pet projects or feature requests could collaborate to 
> create
> a spec to document and guide development?

I already see the headline: PEEP is the answer - PSF votes for software
patents. All ideas are written down by volunteers in great detail they
just have to be coded. Due to intellectual property rights PSF becomes
one of the richest organizations in the world. Guido van Rossum,
chairman of PSF and mighty governor of California recommends an
invasion into Iran: "we cannot accept that they didn't payed us for a
PEEP describing a steering mechism for a nuclear power station to be
written in Python. They are dangerous. They didn't have our
commitment." Mr. van Rossum also commented the unfriendly takeover of
the former software giant Microsoft that was immediately renamed into
"Snakeoil Corp." succinctly: "They had a platform we were interested
in".

Yes, the Python experiment was (not just) successfull.

Kay

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


Re: python for microcontrollers

2005-08-08 Thread Kay Schluehr
Hi Bastard,

one of the main reasons PyPy gets funded by the EU was the promise to
port Python to embedded systems ( but not necessarily very memory
restricted ones ). The project seems to be in a state where the team
tries to get rid of the CPython runtime alltogether and reaching some
autonomy. The idea of providing a Forth backend would fit into the
concept and would be great IMO.

Maybe You should also have a look on the JavaCard platform
specification for inspiration what is possible for an OO language on
time and memory resticted platforms.

http://java.sun.com/products/javacard/specs.html

Since there are vendors that implemented the JVM on smartcards against
SUNs spec and JavaCards are on the market ( not just research
prototypes ) the approach has been proven successfull. For the matter
of memory layout I would naively try to adapt the type inferencer (
annotator in PyPy slang ) and restrict Python to an even more smaller
subset than RPython ( SmartJava does not even support strings. On the
other hand the explicit casting to short and byte types is by no means
braindead ). I currently don't have an idea for memory management and
I'm not even sure about implicit or explicit finalization.

Kay

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


Re: Python -- (just) a successful experiment?

2005-08-08 Thread Kay Schluehr
EP wrote:

> But sometimes a rugged individual can be even more rugged and more individual 
> if said individual has the support of friends by which to vet ideas and, by 
> absorbing counterpoint, to develop one's own thoughts even further.
>
>
> And it is kind of nice when you have two teams drilling a mountain tunnel 
> from opposite sides to have an effective way to line up efforts.

EP, maybe you/we should try out the Meta-SIG or short MESIG which did
not passed away because it was never born.

http://www.python.org/sigs/

In the context of MESIG we can discuss the shape of PEEP and create
your taskforce, blowing life into a new heroic genus - fame and
prestige may be with them. Is K serious? Speaking seriously, a few
years ago K read somewhere in the BDFLs memoirs that "fun" was once a
part of Pythons culture originating from our great anchestors namely
the commedians of Monty Python. Becoming sentimental about this and as
a true and proud reactionary K always seemed to be a fundamentalist
somehow. Not an excuse but an explanation.

Kay

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


Re: Python supports LSP, does it?

2005-08-11 Thread Kay Schluehr

[EMAIL PROTECTED] wrote:
> On Thu, 11 Aug 2005 01:19:19 +0100
> phil hunt wrote:
>
> > According to Wikipedia, the Liskov substitution principle is:
> >
> >   Let q(x) be a property provable about objects x of type T. Then
> >   q(y) should be true for objects y of type S where S is a subtype of T
> >
> > To me, this is nonsense. Under this definition any subtype must
> > behave the same as its parent type, becausde if it doesn't there
> > will be some q(y) that are different to q(x).
> >
> > But if it behaves the same, what's the point of having a subtype?
>
> It does not behave the same, it has the same properties.

Doesn't it?

"What is wanted here is something like the following substitution
property: If
for each object o1 of type S there is an object o2 of type T such that
for all programs P defined in terms of T, the behavior of P is
unchanged when o1 is substituted for o2 then S is a subtype of T."

Barbara Liskov, "Data Abstraction and Hierarchy" SIGPLAN Notices,
23,5 (May, 1988).

IOW if an arbitrary program P works with objects of type T and you
replace each object of type T by an object of type S and each P works
still the same way one can imply that S is a subtype of T.

It is a funny aspect of this definition that it doesn't work for
reflective programming languages. If you have access to properties AS
properties ( on the meta-level ) it is easy to break LSP. Preserving
LSP becomes a challenge or a requirement.

Example:

The statement

if type(obj) == T:
   ...

breaks LSP. One might say that that T has no subtypes at all. But since
T is arbitrary chosen no type in Python has a subtype in a strict
sense.

On the other hand this statement preserves LSP:

if isinstance(obj,T):
   ...

Therefore one can write programs that work as if LSP was valid and
subtypes indeed exist.

Kay

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


Re: Library vs Framework (was Dr. Dobb's Python-URL!)

2005-08-17 Thread Kay Schluehr
Simon Brunning wrote:
> On 8/15/05, Rocco Moretti <[EMAIL PROTECTED]> wrote:
> > Which lead me to the question - what's the difference between a library
> > and a framework?
>
> If you call its code, it's a library. If it calls yours, it's a framework.

Pretty!

I don't think it is an oversimplification. The crucial difference is
that between interface and implementation. A framework forces the
programmers code to conform certain interfaces and contracts. It does
not restrict implementation in any way ( which might be empty ). The
implementation part uses library functions that do not tell much about
the implementation and nothing about interfaces. Libaries give you any
freedom but sometimes ( and only sometimes ) people also like to
structure their code ;)

What are frameworks really good for - a very true success story.

A colleague of mine used to spread all kinds of flags ( state- and
property markers ) over the code that were used to glue everything
together until I raised my tyranny of frameworks. It was a hard
struggle for an OO warrier and took me almost a year or so to become
the undebated projects architect/dictator who trashed all kind of
misguided "freedom" ( i.e. bad code ): "What the fuck is this?" "I
worked almost a week on it!" "It has to be reworked." "No, you don't do
it!" I did it. Who claims that social life is easy? What is nice about
this kind of cruelness is not only my colleague became finally happy
and hopefully learned at least a little bit about programming but also
our customers were gratefull about stable code, thight release
schedules and just-in-time requirement dispatch. Now we have some
bread-and-butter maintenance contract and true freedom to experiment
with other more interesting things besides this. But the struggle just
starts again with the new project ;)

Kay

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


Re: Bug in slice type

2005-08-21 Thread Kay Schluehr
Steven Bethard wrote:

> "The slice of s from i to j with step k is defined as the sequence of
> items with index x = i + n*k such that 0 <= n < (j-i)/k."
>
> This seems to contradict list behavior though.
>  range(10)[9:-1:-2] == []

No, both is correct. But we don't have to interpret the second slice
argument m as the limit j of the above definition. For positive values
of m the identity
m==j holds. For negative values of m we have j = max(0,i+m). This is
consistent with the convenient negative indexing:

>>> range(9)[-1] == range(9)[8]

If we remember how -1 is interpreted as an index not as some limit the
behaviour makes perfect sense.

Kay

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


Re: Proposed PEP: New style indexing, was Re: Bug in slice type

2005-08-21 Thread Kay Schluehr
Bryan Olson wrote:
> Steven Bethard wrote:
>  > Well, I couldn't find where the general semantics of a negative stride
>  > index are defined, but for sequences at least[1]:
>  >
>  > "The slice of s from i to j with step k is defined as the sequence of
>  > items with index x = i + n*k such that 0 <= n < (j-i)/k."
>  >
>  > This seems to contradict list behavior though. [...]
>
> The conclusion is inescapable: Python's handling of negative
> subscripts is a wart. Indexing from the high end is too useful
> to give up, but it should be specified by the slicing/indexing
> operation, not by the value of the index expression.

It is a Python gotcha, but the identity X[-1] == X[len(X)-1] holds and
is very usefull IMO. If you want to slice to the bottom, take 0 as
bottom value. The docs have to be extended in this respect.

Kay

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


Re: Yielding a chain of values

2005-08-31 Thread Kay Schluehr
Reinhold Birkenfeld wrote:

> > x = [ yield r for r in iterable ]
>
> Which is quite different from
>
> x = (yield) in iterable
>
> which is currently (PEP 342) equivalent to
>
> _ = (yield)
> x = _ in iterable
>
> So, no further tinkering with yield, I'm afraid.
>
> Reinhold

Is the statement

   yield from iterable

also in danger to be ambigous?

The resolution of "(yield) from iterable" into

 _ = (yield)
 x = _ from iterable

would not result in valid Python syntax.

Kay

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


Re: Bicycle Repair Man usability

2005-08-31 Thread Kay Schluehr

Sybren Stuvel wrote:

> > -Get rid of extra variables by shifting them inline (e.g.:
> > a=1;b=2;c=a+b --> c=1+2)
>
> This is already excess functionality IMO.

I don't think that Rex talked about his programming style but about
three and only three refactoring methods survived in BRM from ~30
Fowler described in his book. By the way I can't remember the one you
picked up but I remember the reverse i.e. introducing intermediate
variable names for readability and debugging purposes.

Instead of writing f(g(h(...))) it is sometimes adaequate to write

x = h(...)
f(g(x))

I use this a lot in particular in C++. Optimzing compilers eliminate
runtime penalties. This is of course different in CPython.

In case of BRM I'm not sure why it is particular hard to implement
"Move Method" for instance? BRM is shipped with a lot of testcases
which is good but neither defines requirements nor leads a discussion
about refactoring methods in Python. Needless to say that the code is
not well documented. 

Kay

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


Infinity syntax. Re: Bug in string.find; was...

2005-08-31 Thread Kay Schluehr
Bengt Richter wrote:

> How about interpreting seq[i] as an abbreviation of seq[i%len(seq)] ?
> That would give a consitent interpretation of seq[-1] and no errors
> for any value ;-)

Cool, indexing becomes cyclic by default ;)

But maybe it's better to define it explicitely:

seq[!i] = seq[i%len(seq)]

Well, I don't like the latter definition very much because it
introduces special syntax for __getitem__. A better solution may be the
introduction of new syntax and arithmetics for positive and negative
infinite values. Sequencing has to be adapted to handle them.

The semantics follows that creating of limits of divergent sequences:

!0 =  lim n
  n->infinity

That enables consistent arithmetics:

!0+k = lim n+k -> !0
n->infinity

!0/k = lim n/k ->  !0 for k>0,
n->infinity-!0 for k<0
   ZeroDevisionError for k==0


etc.

In Python notation:

>>> !0
!0
>>> !0+1
!0
>>> !0>n# if n is int
True
>>> !0/!0
Traceback (...)
...
UndefinedValue
>>> !0 - !0
Traceback (...)
...
UndefinedValue
>>> -!0
-!0
>>> range(9)[4:!0] == range(9)[4:]
True
>>> range(9)[4:-!0:-1] == range(5)
True

Life can be simpler with unbound limits.

Kay

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


Infinity syntax. Re: Bug in string.find; was...

2005-08-31 Thread Kay Schluehr
Bengt Richter wrote:

> How about interpreting seq[i] as an abbreviation of seq[i%len(seq)] ?
> That would give a consitent interpretation of seq[-1] and no errors
> for any value ;-)

Cool, indexing becomes cyclic by default ;)

But maybe it's better to define it explicitely:

seq[!i] = seq[i%len(seq)]

Well, I don't like the latter definition very much because it
introduces special syntax for __getitem__. A better solution may be the
introduction of new syntax and arithmetics for positive and negative
infinite values. Sequencing has to be adapted to handle them.

The semantics follows that creating of limits of divergent sequences:

!0 =  lim n
  n->infinity

That enables consistent arithmetics:

!0+k = lim n+k -> !0
n->infinity

!0/k = lim n/k ->  !0 for k>0,
n->infinity-!0 for k<0
   ZeroDevisionError for k==0


etc.

In Python notation:

>>> !0
!0
>>> !0+1
!0
>>> !0>n# if n is int
True
>>> !0/!0
Traceback (...)
...
UndefinedValue
>>> !0 - !0
Traceback (...)
...
UndefinedValue
>>> -!0
-!0
>>> range(9)[4:!0] == range(9)[4:]
True
>>> range(9)[4:-!0:-1] == range(5)
True

Life can be simpler with unbound limits.

Kay

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


Re: Infinity syntax. Re: Bug in string.find; was...

2005-08-31 Thread Kay Schluehr
Bengt Richter wrote:

> >>>> range(9)[4:-!0:-1] == range(5)
> >True
> Interesting, but wouldn't that last line be
>  >>> range(9)[4:-!0:-1] == range(5)[::-1]

Ups. Yes of course.

> >Life can be simpler with unbound limits.
> Hm, is "!0" a di-graph symbol for infinity?
> What if we get full unicode on our screens? Should
> it be rendered with unichr(0x221e) ? And how should
> symbols be keyed in? Is there a standard mnemonic
> way of using an ascii keyboard, something like typing
> Japanese hiragana in some word processing programs?

You can ask questions ;-)

> I'm not sure about '!' since it already has some semantic
> ties to negation and factorial and execution (not to mention
> exclamation ;-)  If !0 means infinity, what does !2 mean?
>
> Just rambling ... ;-)

I'm not shure too. Probably Inf as a keyword is a much better choice.
The only std-library module I found that used Inf was Decimal where Inf
has the same meaning. Inf is quick to write ( just one more character
than !0 ) and easy to parse for human readers. Rewriting the above
statements/expressions leads to:

>>> Inf
Inf
>>> Inf+1
Inf
>>> Inf>n# if n is int
True
>>> Inf/Inf
Traceback (...)
...
UndefinedValue
>>> Inf - Inf
Traceback (...)
...
UndefinedValue
>>> -Inf
-Inf
>>> range(9)[4:Inf] == range(9)[4:]
True
>>> range(9)[4:-Inf:-1] == range(5)[::-1]
True

IMO it's still consice.

Kay

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


Re: Yielding a chain of values

2005-08-31 Thread Kay Schluehr
Reinhold Birkenfeld wrote:
> Kay Schluehr wrote:
> > Reinhold Birkenfeld wrote:
> >
> >> >  x = [ yield r for r in iterable ]
> >>
> >> Which is quite different from
> >>
> >> x = (yield) in iterable
> >>
> >> which is currently (PEP 342) equivalent to
> >>
> >> _ = (yield)
> >> x = _ in iterable
> >>
> >> So, no further tinkering with yield, I'm afraid.
> >>
> >> Reinhold
> >
> > Is the statement
> >
> >yield from iterable
> >
> > also in danger to be ambigous?
> >
> > The resolution of "(yield) from iterable" into
> >
> >  _ = (yield)
> >  x = _ from iterable
> >
> > would not result in valid Python syntax.
>
> Right.
>
> Problem is, how would you define the "from" syntax: Is its use as
> an expression allowed? What value does it have, then?
>
> Reinhold

Do you mention statements like this?

   x = (yield from [1,2,3])

I do think that such "yield-comprehensions" may be valid and raise a
StopIteration exception after being called three times by means of
next() or send(). 

Kay

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


Re: Epydoc - Documenting class members?

2005-08-31 Thread Kay Schluehr
This should help:

http://epydoc.sourceforge.net/fields.html

Kay

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


PEP-able? Expressional conditions

2005-09-07 Thread Kay Schluehr
One of the main reasons Pythons anonymous function lambda is considered
to be "broken" is Pythons disability to put statements into expressions
and support full functionality. Many attempts to improve lambdas syntax
had also been attempts to break the expression/statement distinction in
one or the other way. None of this suggestions have ever been
successfull in solving severe problems caused by Pythons indentation
syntax and I guess they will never succeed. On the other hand I do not
see immediately the necessaty to support the full range of Python
constructs in small anonymous functions that are dedicated to fit into
one line.

Instead of pushing statements into expressions one can try to do it the
other way round and model expressions with the functionality of
statements. The most important use-cases are assignments and
conditions. I want to consider conditions only.

In Python conditional statements have the form:

if COND_1:
   BLOCK_1
elif COND_2:
   BLOCK_2
...
else:
   BLOCK_n

Before turning this kind of statement into an expression we have to
restrict the BLOCKs to expressions:

if COND_1:
   EXPR_1
elif COND_2:
   EXPR_2
...
else:
   EXPR_n

Since the conditional statement is traversed sequentially we can
transform it into a sequence of (COND,EXPR) pairs. Finally we have to
recover the conditional semantics.

I want to propose a new associative binary operator that acts on
(COND,EXPR) pairs like a projection on the second EXPR argument of a
pair in case of COND evaluated True.

This function works much like

def cond(pair1, pair2):
COND1,EXPR1 = pair1
if COND1:
return EXPR1
try:
COND2,EXPR2 = pair2
if COND2:
return EXPR2
except TypeError:
return pair2


Alternative syntax proposals:

(a)   (COND1,EXPR1) || (COND2,EXPR2)
(b)   (COND1,EXPR1) case (COND2,EXPR2)
(c)   (COND1,EXPR1) owise (COND2,EXPR2)
(d)   (COND1,EXPR1) ? (COND2,EXPR2) 

Regards,
Kay

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


Re: PEP-able? Expressional conditions

2005-09-07 Thread Kay Schluehr
Terry Hancock wrote:
> On Wednesday 07 September 2005 05:29 am, Kay Schluehr wrote:
> > Instead of pushing statements into expressions one can try to do it the
> > other way round and model expressions with the functionality of
> > statements.
>
> > Alternative syntax proposals:
> >
> > (a)   (COND1,EXPR1) || (COND2,EXPR2)
> > (b)   (COND1,EXPR1) case (COND2,EXPR2)
> > (c)   (COND1,EXPR1) owise (COND2,EXPR2)
> > (d)   (COND1,EXPR1) ? (COND2,EXPR2)
>
> You appear to be reinventing the C "ternary operator".  This is
> definitely a dead horse. There was already a PEP, and it was
> refused.

Well, I'm not inspired by C and the operator is not ternary but binary
and associative. Nevertheless the behaviour of the ternary condition
operator exists as a limit case. The expression becomes more a kind of
a horizontal squeezed switch. Therefore the "case" keyword proposal.

It might become more obvious if one chains the expression using more
terms:

(a') (COND1,EXPR1) || (COND2,EXPR2) || ... || (CONDk,EXPRk)
(b') (COND1,EXPR1) case (COND2,EXPR2) case ... case (CONDk,EXPRk)

> If you actually want this, you're going to have to implement it
> with a function:
>
> def ternary(condition, true_result, false_result):
>   if condition:
>   return true_result
>   else:
>   return false_result

No, as I explained it is not a ternary operator and it can't easily be
implemented using a Python function efficiently because Python does not
support lazy evaluation. One usually does not want to evaluate all
conditions as well as all the results ( when passing them into the
function ) but evaluate conditional expressions sequentially and stop
at the first true condition. Well I would indeed like to go even
further and introduce lazy tuples this way but I wanted to notice the
responses to an obvious use case first.

Kay

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


Re: PEP-able? Expressional conditions

2005-09-07 Thread Kay Schluehr
Terry Reedy wrote:
> "Kay Schluehr" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > No, as I explained it is not a ternary operator and it can't easily be
> > implemented using a Python function efficiently because Python does not
> > support lazy evaluation.
>
> By *carefully* using the flow-control operators 'and' and 'or', you can
> often get what you want *now*, no PEP required.
>
> > One usually does not want to evaluate all
> > conditions as well as all the results ( when passing them into the
> > function ) but evaluate conditional expressions sequentially and stop
> > at the first true condition.
>
> *If* bool(result_expression_i) ==  True for all i, (except maybe last
> default expression), which is true for some actual use cases, then the
> following expression evaluates to the result corresponding to the first
> 'true' condition (if there is one) or to the default:
>
> c0 and r0 or c1 and r1 or c2 and r2... or default.
>
> I have only seen real examples with one and-pair, like (x < 0) and -x or x
> for absolute value.
>
> Terry J. Reedy

O.K. you win. One can complete this particular evaluation scheme by
introducing a little wrapper:

def Id(val):
return lambda:val

(c0 and Id(r0) or c1 and Id(r1) or c2 and Id(r2)... or Id(default))()

This works for each sequence r0,r1,... without any restictions. 

Kay

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


Re: Yielding a chain of values

2005-09-07 Thread Kay Schluehr
[EMAIL PROTECTED] wrote:

> dude - this business is so confusing that you actually have to *think*
> about it!
> but python is all about simplicity.
> with python, when I program - I don't think *about* it - I think it. or
> something - don't make me think about it.
>
> so how about a "reyield" or some other new keyword (cause reyield is
> too quircky) instead of joining stuff which once ment something (one
> thing)?

What about dleiy? I guess it thinks me.

Kay

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


Re: Migrate PYD Files

2005-09-08 Thread Kay Schluehr
David Duerrenmatt wrote:
> Is there a way to use old pyd files (Python 1.5.2) with a newer version
> of Python without recompiling them?
>
> Because the source code is not available anymore, I'm wondering whether
> it's possible or not to change few bytes with a hex editor (version
> number?). I'd like to give it a try since the modules don't use too
> critical functions.
>
> Thanks
> dd

Hi David,

you might checkout embedding your Python 1.5.2 interpreter into Python
using ctypes. Just follow chap.5 of the "Extending and Embedding"
tutorial and the docs of the cytpes API.

The following little script runs successfully on Python23 interpreter.

==

import ctypes
python24 = ctypes.cdll.LoadLibrary("python24.dll")
python24.Py_Initialize()
python24.PyRun_SimpleString("from time import time,ctime\n")
python24.PyRun_SimpleString("print 'Today is',ctime(time())\n");
python24.Py_Finalize()

Kay

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


Re: Question about consistency in python language

2005-09-08 Thread Kay Schluehr
[EMAIL PROTECTED] wrote:

> Let's say I define a list of pairs as follows:
> >>l = [('d', 3), ('a', 2), ('b', 1)]
>
> Can anyone explain why this does not work?
> >>h = {}.update(l)
>
> and instead I have to go:
> >>h = {}
> >>h.update(l)
> to initialize a dictionary with the given list of pairs?
>
> when an analagous operation on strings works fine:
> >>s = "".join(["d","o","g"])
>
> Seems inconsistent.

If you define

>>> sep = ""
>>> sep.join(["d","o","g"])
"dog"
>>> sep
''

sep is preserved and a new "dog" string is generated. Since sep is
immutable there is no way to manipulate it inplace.

On the other hand there exists no sorted() method for tuples or lists
like join() for strings but it is implemented as a function in Python24
that returns a new sorted container. I consider this as an
inconsistency across builtin types. Consistent would be following usage
pattern:

>>> l = [1,3,2]
>>> l.sorted()
[1,2,3] # new sorted list
>>> l.sort()# sort list inplace
>>> l.appended(4)   # new extended list
[1,2,3,4]
>>> l.append(4) # appends an element to the same list
>>> l
[1,2,3,4]

Preserving the naming convention we would have

>>> "".joined(["d","o","g"])
"dog"

Kay

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


Re: Question about consistency in python language

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

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

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

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

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

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

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

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

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

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

Kay

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


Re: Question about consistency in python language

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

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

Kay

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


Re: Why do Pythoneers reinvent the wheel?

2005-09-10 Thread Kay Schluehr
Tim Daneliuk wrote:

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

Allthough I do think that you are completely wrong in principle there
is some true point in your statement: refactoring a foreign ill
designed tool that nevertheless provides some nice functionality but is
not mentioned for being extendable by 3-rd party developers is often
harder than writing a nice and even though inextendable tool on your
own. That's independent of the language allthough I tend to think that
C and Python programmers are more alike in their crude pragmatism than
Java or Haskell programmers ( some might object that it is a bit unfair
to equate Java and Haskell programmers, because no one ever claimed
that the latter need code-generators and no intelligence to do their
work ).

Kay

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


Re: Question about consistency in python language

2005-09-11 Thread Kay Schluehr

Steve Holden wrote:
> Kay Schluehr wrote:
> > Mike Meyer wrote:
> >
> >
> >>Yes, but the function "sorted" is more useful than a list method
> >>"sorted" in a duck typing language.
> >
> >
> > I don't see what this has to do with "duck typing"? sorted() is simply
> > a generic function accepting different types. I'm not aware that
> > sorted() requires a specific interface of those types it accepts.
> >
> Just because you aren't aware of something doesn't stop it being true.
> The argument must be iterable, and there's a specific protocol for that.
> >
> >>The function sorted works on all iterators. I can do:
> >>
> Ah, so you *were* aware of it.

I already responded to it two days ago in the reply to Terry. No need
to rehash that.

> >>
> >>>>>def t(n):
> >>>>>  for i in range(n):
> >>>>>yield i
> >>>>>...
> >>>>>print sorted(t(5))
> >>
> >>and have it work.
> >>
> >>If sorted were a method of a class - the it'd have to be implemented
> >>again for every class iterable class. Either that, or you'd have to
> >>create an abstract parent of all iterable classes to add it to - which
> >>seems more appropriate for a B&D language than Python.
> >
> >
> > Instead of extending a class hierarchy it might even be possible to
> > hook a trait into the class by means of a __traits__ attribute.
> >
> > http://fsl.cs.uiuc.edu/~mhills/presentations/TraitsPresentation.pdf
> >
> > Generators as well as lists and tuples would provide a sortable trait.
> > The sorted() function could remain available for convenience.
> >
> The advantage being ... ? Perhaps you have just discovered a really
> interesting hammer, and are seeing this problem as a nail?

I also responded to traits as nice-to-have but not essential. And
please don't aggressively consider me as childish as you might be
yourself.

Adding a __traits__ attribute should enable the user adding methods to
builtins in a safe manner. This has the advantage that one can apply
methods to string or integer literals or even replace methods without
touching the C sources. A very typical use case is integer
representation. In 95% of all my business applications I don't have
much use for decimal integer representation but want a hex rep in
different variants:

>>> 0x0F  # current rep
15

>>> int.__traits__.append(HexRepTrait)  # used for delegation of
# __repr__ to the Trait
>>> int.configure_format(HexRepTrait.HEXFORM_STD) # configure_format is a
  # hooked trait method
>>> 0x0F
0F
>>> 2*0x800
10 00
>>> print 700
02 BC

I know I can write wrapper classes, because I do this all the time, but
that's not the point: Python is essentially not about boiler-plate. And
no, I also don't want to fight for each method and keyword with Guido.

> >
> >>And even if you do add the abstract class, how do you make my example
> >>work without explictly converting the iterator to a list type?
> >
> >
> > I don't know how sorted() is implemented? A naive implementation would
> > in fact be nothing else then:
> >
> > def sorted(iter):
> > l = list(iter)
> > l.sort()
> > return l
> >
> > Kay
> >
> That would indeed be a naïve implementation.

And that's the real implementation:

static PyObject *
builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
PyObject *callable;
static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
long reverse;

if (args != NULL) {
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
kwlist, &seq, &compare, &keyfunc, &reverse))
return NULL;
}

newlist = PySequence_List(seq);
if (newlist == NULL)
return NULL;

callable = PyObject_GetAttrString(newlist, "sort");
if (callable == NULL) {
Py_DECREF(newlist);
return NULL;
}

newargs = PyTuple_GetSlice(args, 1, 4);
if (newargs == NULL) {
Py_DECREF(newlist);
Py_DECREF(callable);
return NULL;
}

v = PyObject_Call(callable, newargs, kwds);
Py_DECREF(newargs);
Py_DECREF(callable);
if

Re: Grouping lists

2005-09-12 Thread Kay Schluehr

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

Hi,

I got a solution without iterators and without comparing adjecent
elements! O.K. it is neither the most efficient nor the most obvious
solution but I didn't want to get bored ;)

import sets

l = [1,1,8,1,1,3,5,1,1,1,1,7,7,7]
regions = []

for x in sets.Set(l):
start = l.index(x,0)
cnt = 0
while 1:
try:
idx = l.index(x,start)
if idx!=start:
regions.append((start-cnt,start-1))
cnt   = 0
start = idx
else:
cnt+=1
start+=1
except ValueError:
regions.append((start-cnt,start-1))
break

regions.sort()

This returns [(0, 3), (4, 4), (5, 5), (6, 9), (10, 12)]

Now splitting l in regions:

>>> [l[i:j+1] for (i,j) in regions]
[[1, 1, 1, 1], [3], [5], [1, 1, 1, 1], [7, 7, 7]] 

Kay

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


Re: Self reordering list in Python

2005-09-15 Thread Kay Schluehr
Laszlo Zsolt Nagy wrote:
> Hello,
>
> Do you know how to implement a really efficient self reordering list in
> Python? (List with a maximum length. When an item is processed, it
> becomes the first element in the list.) I would like to use this for
> caching of rendered images.

I wonder why you don't use a dictionary? The only time I used a
move-front algorithm I stored algorithms and had to evaluate a
condition to select the correct algo. That means no constant search key
was available for accessing the correct one. In case of an image list I
would implement a self-ordering list if I have to do some pattern
recognition in order to select the correct image. Holding a reference
as a search key a Python hash-table will always have a better average
time complexity no matter which language is used to implement
move-front. In either way I'd use Python as an implementation language.


Kay

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


  1   2   3   4   5   6   7   8   >