Re: Wrapping classes

2005-09-23 Thread Paolino
Jeremy Sanders wrote:
> Is it possible to implement some sort of "lazy" creation of objects only
> when the object is used, but behaving in the same way as the object?
> 
A generic approach would override __getattribute__ to let it perform the 
  __init__ method on not initialized objects.This is a case for using 
metaclasses as even __init__ method must be overridden ad hoc to 
register the arguments for the lazy initialization.
Probably you want to fine-tune the triggering (specifing which attribute 
should make it happen ),as every look up would trigger.

class NotInitializedObjects(type):
   def __init__(cls,*_):
 realInit=cls.__init__
 def __newInit__(self,*pos,**key):
   def _init():
 realInit(self,*pos,**key)
   self._init=_init
 cls.__init__=__newInit__
 def __getattribute__(self,attr):
   def getter(attr):
 return object.__getattribute__(self,attr)
   if '_init' in getter('__dict__'):
 getter('_init')()
 del self._init
   return getter(attr)
 cls.__getattribute__=__getattribute__


if __name__=='__main__':
   class Class:
 __metaclass__=NotInitializedObjects
 def __init__(self,*pos,**key):
   self.initialized=True
   print 'initializing with',pos,key
   a=Class('arg',key='key') # a fake initialization

   try:
object.__getattribute__(a,'initialized')
   except AttributeError: # should raise
print 'not initialized'
   else:
raise
   try:
a.initialized  #every look up would do ,even a print
   except AttributeError:
raise
   else:
print 'initialized'


Have fun Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping classes

2005-09-23 Thread Paolino
Paolino wrote:

> class NotInitializedObjects(type):
>   def __init__(cls,*_):
> realInit=cls.__init__
> def __newInit__(self,*pos,**key):
>   def _init():
> realInit(self,*pos,**key)
>   self._init=_init
> cls.__init__=__newInit__
> def __getattribute__(self,attr):
>   def getter(attr):
> return object.__getattribute__(self,attr)
>   if '_init' in getter('__dict__'):
> getter('_init')()
> del self._init
>   return getter(attr)
> cls.__getattribute__=__getattribute__
> 

A lighter solution can be overriding __getattr__.
This will produce more object-like behaving instances even when not 
initialized, aka you can call methods and access class attributes 
without triggering the init (not very useful)

class NotInitializedObjects(type):
   def __init__(cls,*_):
 realInit=cls.__init__
 def __newInit__(self,*pos,**key):
   def _init():
 realInit(self,*pos,**key)
   self._init=_init
 cls.__init__=__newInit__
 def __getattr__(self,attr):
   if hasattr(self,'_init'):
 self._init()
 del self._init
 if hasattr(self,attr):
   return getattr(self,attr)
   raise AttributeError
 cls.__getattr__=__getattr__

### Test with previous testing code

A cleaner solution is decoupling the intensive calculation attributes 
from __init__ and use descriptors for them.But this is impossible if 
/the/ instance value is the intensive one to be calculated.

Ciao Paolino



___ 
Aggiungi la toolbar di Yahoo! Search sul tuo Browser, e'gratis! 
http://it.toolbar.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a dictionary from an object

2005-07-23 Thread Paolino
Thanos Tsouanas wrote:
> Hello.
> 
> I would like to have a quick way to create dicts from object, so that a
> call to foo['bar'] would return obj.bar.
> 
> The following works, but I would prefer to use a built-in way if one
> exists.  Is there one?
> 

> class dictobj(dict):
> """
> class dictobj(dict):
> A dictionary d with an object attached to it,
>   which treats d['foo'] as d.obj.foo.
> """
> def __init__(self, obj):
> self.obj = obj
> def __getitem__(self, key):
> return self.obj.__getattribute__(key)
use getattr(self.obj,key) possibly, as __getattribute__ gets total 
control on attribute access





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Aliasing" an object's __str__ to a different method

2005-07-23 Thread Paolino
Little less ugly:
In [12]:class A(object):
: def __str__(self):return self.__str__()
: def str(self):return 'ciao'
: def setStr(self):self.__str__=self.str
:

In [13]:a=A()

In [14]:a.setStr()

In [15]:str(a)
Out[15]:'ciao'

The point is str(ob) builtin looks like calling 
ob.__class__.__str__(ob).Prolly Python-dev is the good place to ask about.







___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a dictionary from an object

2005-07-23 Thread Paolino
Thanos Tsouanas wrote:
> On Sat, Jul 23, 2005 at 12:06:57PM +0200, Paolino wrote:
> 
>>use getattr(self.obj,key) possibly, as __getattribute__ gets total 
>>control on attribute access
> 
> 
> Thanks, but what do you mean by 'total control'?
> 
Probably nothing to do with your question :(
But:
 >>> class A(object):
...   def __getattr__(self,attr):
... return 'whatever'
...
 >>> a=A()
 >>> a.b
'whatever'
 >>> getattr(a,'b')
'whatever'
 >>> a.__getattribute__('b')
Traceback (most recent call last):
   File "", line 1, in ?
AttributeError: 'A' object has no attribute 'b'
 >>>

This can probably touch you if your objects uses defualt searching for 
attributes.






___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create a variable "on the fly"

2005-07-27 Thread Paolino
Paul D.Smith wrote:
> Can Python create a variable "on-the-fly".  For example I would like
> something like...
> 
> make_variable('OSCAR', 'the grouch');
> print OSCAR;
> 
> ...to output...
Python has only 'on the fly' variables and ';' is not used for one 
expression in one line.


Probably the tutorial is good to be read also.

Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create a variable "on the fly"

2005-07-27 Thread Paolino
Paul D.Smith wrote:
> Can Python create a variable "on-the-fly".  For example I would like
> something like...
> 
> make_variable('OSCAR', 'the grouch');
> print OSCAR;
> 
> ...to output...
Python has only 'on the fly' variables and ';' is not used for one 
expression in one line.


Probably the tutorial is good to be read also.

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


Re: any thing to do???

2005-07-27 Thread Paolino
mustafa wrote:
> i hav just finished learning pythob from "A byte of python"(an online 
> book) so i wanted to apply my new skills. to learn and to have some fun.
> is there any place which lists jobs to be done...you know minor jobs and 
> requests thats nobody has found time to do.
> i would point out that i am not looking for a JOB as job with payment.
> i am looking for a JOB that is to be done and nobody has done it yet.
> 
> also aside from this is there any other way i could use python and 
> improve. i figure this practice will make me a lot better. but if anybody
> else has any ideas than that would be good too .
> 
Hmm try this:
  http://www.itasoftware.com/careers/eng/job1.php

For really useful things probably you want to reach some projects like 
twisted ,but there you need more experience IMO. Good luck and welcome 
to Python.

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


Re: [Beginner] Calling a function by its name in a string

2005-07-27 Thread Paolino
Tito wrote:
> Hi all:
> 
> Is there a metalanguage capability in Python (I know there are many) to 
> call a function having its name in a string?
> 
> Something like:
> __call__("foo")
> 
> instead of:
> foo()
> 
> Regards,
> Tito
eval('foo()') should do, but it's said a bad practice ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can list comprehensions replace map?

2005-07-27 Thread Paolino
David Isaac wrote:
> Newbie question:
> 
> I have been generally open to the proposal that list comprehensions
> should replace 'map', but I ran into a need for something like
> map(None,x,y)
> when len(x)>len(y).  I cannot it seems use 'zip' because I'll lose
> info from x.  How do I do this as a list comprehension? (Or,
> more generally, what is the best way to do this without 'map'?)

Probably zip should change behaviour,and cover that case or at least 
have another like 'tzip' in the __builtins__ .Dunno, I always thought 
zip should not cut to the shortest list.
> Thanks,
> Alan Isaac
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping a class set method

2005-07-27 Thread Paolino
snoe wrote:


> I have a suspicion that there's an easier way to do this than
> explicitly adding a Project.pickleme() call to the beginning of all of
> my set/add methods.

> So is there a way to wrap methods for this type of functionality or is
> there another way of doing this, maybe without using setter methods?


I guess you are pointing to decorators, anyway you have to explicitly 
wrap methods that are supposed to pickle.
Another way around is implement a metaclass and give the pickling 
methods a special start name like set_ or add_ ,so having a protocol for 
writing methods names.I paste the __metaclass__ solution

  this is a skeleton

def saveStateWrapper(method,states):
   from copy import copy
   def wrapper(self,*_,**__):
 self.__undoings.append(map(copy,[getattr(self,state) for state in 
states])) # copy can not be idoneous
 return method(self,*_,**__)
   return wrapper

def initWrapper(init):
   def wrapper(self,*_,**__):
 self.__undoings=[]
 init(self,*_,**__)
   return wrapper

def undo(self): # an undoing method
   if self.__undoings:
 for state,was in zip(self.states,self.__undoings.pop(-1)):
   setattr(self,state,was)

class Undoable(type): # the metaclass
   def __init__(cls,name,bases,attrs):
  cls.__init__=initWrapper(cls.__init__) # wrap init to add an 
attribute __undoings to the instances
  for attr in dir(cls):
 if attr.split('_')[0] in ('add','set'): # look for attributes 
protocolleds
 
setattr(cls,attr,saveStateWrapper(getattr(cls,attr),cls.states)) # wrap 
methods
  cls.undo=undo #add the undo method

class Project(object):
 __metaclass__=Undoable
 states=['pname','devices']

 def __init__(self,pname):
 self.devices = set()
 self.pname = pname
 def set_pname(self,pname):
 self.pname = pname
 def lookFor(self,dname): # names can change in the devices instances
 for device in self.devices:  # add exceptions checkings
   if device.dname==dname:
 return device
 def add_device(self,dname):
 self.devices.add(Device(self,dname))

class Device(object):
 __metaclass__=Undoable
 states=['dname']
 def __init__(self,parent,dname):
 self.parent = parent
 self.dname = dname
 def set_dname(self,dname):
 self.dname = dname

project=Project('pippo')
project.set_pname('pupo')
assert project.pname=='pupo'
project.undo()
assert project.pname=='pippo'
project.add_device('aargh')
device=project.lookFor('aargh')
device.set_dname('sperem')
assert device==project.lookFor('sperem')
device.undo()
assert device==project.lookFor('aargh')  ## :)
project.undo()






___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping a class set method

2005-07-27 Thread Paolino
snoe wrote:


> I have a suspicion that there's an easier way to do this than
> explicitly adding a Project.pickleme() call to the beginning of all of
> my set/add methods.

> So is there a way to wrap methods for this type of functionality or is
> there another way of doing this, maybe without using setter methods?


I guess you are pointing to decorators, anyway you have to explicitly 
wrap methods that are supposed to pickle.
Another way around is implement a metaclass and give the pickling 
methods a special start name like set_ or add_ ,so having a protocol for 
writing methods names.I paste the __metaclass__ solution

  this is a skeleton

def saveStateWrapper(method,states):
   from copy import copy
   def wrapper(self,*_,**__):
 self.__undoings.append(map(copy,[getattr(self,state) for state in 
states])) # copy can not be idoneous
 return method(self,*_,**__)
   return wrapper

def initWrapper(init):
   def wrapper(self,*_,**__):
 self.__undoings=[]
 init(self,*_,**__)
   return wrapper

def undo(self): # an undoing method
   if self.__undoings:
 for state,was in zip(self.states,self.__undoings.pop(-1)):
   setattr(self,state,was)

class Undoable(type): # the metaclass
   def __init__(cls,name,bases,attrs):
  cls.__init__=initWrapper(cls.__init__) # wrap init to add an 
attribute __undoings to the instances
  for attr in dir(cls):
 if attr.split('_')[0] in ('add','set'): # look for attributes 
protocolleds
 
setattr(cls,attr,saveStateWrapper(getattr(cls,attr),cls.states)) # wrap 
methods
  cls.undo=undo #add the undo method

class Project(object):
 __metaclass__=Undoable
 states=['pname','devices']

 def __init__(self,pname):
 self.devices = set()
 self.pname = pname
 def set_pname(self,pname):
 self.pname = pname
 def lookFor(self,dname): # names can change in the devices instances
 for device in self.devices:  # add exceptions checkings
   if device.dname==dname:
 return device
 def add_device(self,dname):
 self.devices.add(Device(self,dname))

class Device(object):
 __metaclass__=Undoable
 states=['dname']
 def __init__(self,parent,dname):
 self.parent = parent
 self.dname = dname
 def set_dname(self,dname):
 self.dname = dname

project=Project('pippo')
project.set_pname('pupo')
assert project.pname=='pupo'
project.undo()
assert project.pname=='pippo'
project.add_device('aargh')
device=project.lookFor('aargh')
device.set_dname('sperem')
assert device==project.lookFor('sperem')
device.undo()
assert device==project.lookFor('aargh')  ## :)
project.undo()

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


Re: can list comprehensions replace map?

2005-07-27 Thread Paolino
Raymond Hettinger wrote:
> [David Isaac]
> 
>>>I have been generally open to the proposal that list comprehensions
>>>should replace 'map', but I ran into a need for something like
>>>map(None,x,y)
>>>when len(x)>len(y).  I cannot it seems use 'zip' because I'll lose
>>>info from x.  How do I do this as a list comprehension? (Or,
>>>more generally, what is the best way to do this without 'map'?)
> 
> 
> [Paolino]
> 
>>Probably zip should change behaviour,and cover that case or at least
>>have another like 'tzip' in the __builtins__ .Dunno, I always thought
>>zip should not cut to the shortest list.
> 
> 
> Heck no!  For the core use case of lockstep iteration, it is almost
> always a mistake to continue iterating beyond the length of the
> shortest input sequence.  Even for map(), the use cases are thin.  How
> many functions do something meaningful when one or more of their inputs
> changes type and becomes a stream of Nones.  Consider for example,
> map(pow, seqa, seqb) -- what good can come of one sequence or the other
> suddenly switching to a None mode?
> 
> As Andrew pointed out, if you really need that behavior, it can be
> provided explicity.  See the padNone() recipe in the itertools
> documentation for an easy one-liner.
> 
> IMO, reliance on map's None fill-in feature should be taken as a code
> smell indicating a design flaw (not always, but usually).  There is a
> reason that feature is missing from map() implementations in some other
> languages.
> 
> In contrast, the existing behavior of zip() is quite useful.  It allows
> some of the input sequences to be infinite:
> 
>zip(itertools.count(1), open('myfile.txt'))
> 
Right point.
Well, for my little experiences use cases in which the lists have different
lengths are rare, but in those cases I don't see the reason of not being 
able
to zip to the longest one.What is really strange is that I have to use
map(None,) for that,instead of another zip-like function which ,at 
least
would be intutitive for the average user.Also map(None,...) looks like a 
super-hack
and it's not elegant or readable or logic (IMO)

I think zip comes to substitute the tuple.__new__ untolerant 
implementation.A dumb like me wuold expect map(tuple,[1,2,3],[2,3,4]) to 
work, so pretending map(None,) would do it is like saying that None 
and tuple are near concepts, which is obviously an absurdity.

Thanks anyway, for explanations.

Paolino

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


Mailing list question

2005-07-28 Thread Paolino
Puzzling.

I have subscribed this list with an address int the gmail.com domain,
and I receive your postings there,but it seems I can send messages with 
THIS address ,and I don't receive my messages sent with the gmail account.
I don't receive any "python.org mailing list memberships reminder" on 
this address, while I receive in the gmail one.
I didn't touch the options ,so I should receive my messages.

Sinking in the sea of impotence.


Thanks for help





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Advanced concurrancy

2005-07-28 Thread Paolino
Peter Tillotson wrote:
> Hi,
> 
> I'm looking for an advanced concurrency module for python and don't seem 
> to be able to find anything suitable. Does anyone know where I might 
> find one? I know that there is CSP like functionality built into 
> Stackless but i'd like students to be able to use a standard python build.
> 
> I'm trying to develop distributed / Grid computing modules based on 
> python. The aim is to be able to use barriers for synchronisation and 
> channels for communication between processes running on a single box. 
> Then the jump to multiple processes on multiple boxes and eventually to 
> MPI implementations. Hopefully, each jump should not be that big a leap.
> 
> Of course it would be nice if there was a robust way of managing 
> concurrency in python aswell ;-)
>


And deferredGenerator in twisted.internet.defer is the robust way for that.
It blows up python readability in contrast,but once you got them and 
made your library I think they are also usable.
I do believe, without deferreds in the core ,python will have bad times 
surviving the net, but that's really an opinion.

Have fun, Paolino

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


Re: Determine if object is a Bound or Unbound method

2005-07-28 Thread Paolino
Farshid Lashkari wrote:
> Hi,
> 
> I have an object and I want to check if it is a bound or unbound method, 
> or neither. I tried using the types module, but it seems as though 
> types.UnboundMethodType and types.MethodType are equal. How else can I 
> determine this? BTW, I'm using Python 2.3
> 
> Thanks,
> 
> Farshid
Bound methods has an im_self attribute set to the instance binding them

Ciao


___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why functions in modules need 'global foo' for integer foo but not dictionary foo?

2005-07-28 Thread Paolino
Robert Kern wrote:
> [EMAIL PROTECTED] wrote:
> 
>>At top of a module I have an integer like so...
>>
>>foo = 4
>>
>>In a function in that module I know I need to do 'global foo' to get at
>>the value 4.
>>...
> 

> 
> I presume you are trying code like the following:
> 
> foo = 4
> bar = {}
> 
> def fun1():
>  foo = 5
> 
> def fun2():
>  bar['baz'] = 4
> 
> Since integers are immutable, all that fun1() does is assign 5 to the 
> name "foo" within fun1()'s namespace and doesn't touch the module-level 
> namespace.
Hmm this is obscure to me also, what mutables has to do with this 
problem?A binding is always mutable.

> fun2(), on the other hand, only gets the dictionary from the 
> module-level namespace with the name "bar". Then it modifies that 
> dictionary (since it's mutable). It does not try to assign a new object 
> to the name "bar".

Probably the point is modifing/rebinding  the bound values and not 
rebind them.

Generally if you need to use globals for inter-instance/class 
communication, I suggest to define a new namespace where
to put global  bindings:

class Globals:
   foo=4
   spam={}

for lexical coherence you can put also funtions there

class Globals:
   foo=4
   spam={}

   @staticmethod
   def func():pass

then you always refer to them with Globals.foo,Globals.spam,Globals.func 
  or with .Globals  from outside.

Finally consider to use singletons as a more common approach.

Ciao





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten Essential Development Practices

2005-07-29 Thread Paolino
[EMAIL PROTECTED] wrote:
> The following url points to an article written by Damian Conway
> entitled "Ten Essential Development Practices":
> http://www.perl.com/pub/a/2005/07/14/bestpractices.html
> 
> Althought the article has Perl as a focus, I thought that some of the
> general points made might be of interest to the Python community. It
> would certainly be interesting to put together an analogous version of
> this article that centers on Python.
> 
Hmm, Perl is called a write once language, but it has thousands of 
libraries.Any comment appreciated.

That said,those points are mixing different responsabilities in writing 
code.I keep on mixing for fun:

-Writing libraries is not writing scripts.
-Writing readable,well structured,non redundant code is somewhat 
perpendicular to tests.
-Writing tests is a must for more people to work on the same code.
-Deciding the interface and writing docs before coding can be bad for 
experimental coding.
-Logic optimization can influence interfaces.
-Time optimization is a leverage to get paid in open source 
software.Never think about that for free.

Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A replacement for lambda

2005-07-30 Thread Paolino
why (x**2 with(x))<(x**3 with(x)) is not taken in consideration?

If 'with' must be there (and substitue 'lambda:') then at least the 
syntax is clear.IMO Ruby syntax is also clear.





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


namespaces

2005-07-31 Thread Paolino
While it's not so bad we can bind names in the module namespace, (ex 
writing  scripts ?) ,writing modules is someway bound to not polluting 
that namespace (really IMO).

For non-functions we can use 'class' :

class ns:
   foo='something'

but writing a function there triggers the binding to 'self' behaviour.

The straight solution is @staticmethod

class ns:
   @staticmethod
   def gulp(*args):
 pass

Another solution is via metaclass

class namespaceMeta(type):
   def __init__(cls,*more):
 ## wrap all methods with staticmethod()
class namespace:
   __metaclass__=namespaceMeta

class ns(namespace):
   def gulp(*args):pass

This solution makes me think the keyword 'namespace' is missing:

namespace ns:
   foo='something'
   def gulp(*args):
 pass

Solutions and comments appreciated.

Regards Paolino


___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-07-31 Thread Paolino
Robert Kern wrote:
> Paolino wrote:
> 
>>While it's not so bad we can bind names in the module namespace, (ex 
>>writing  scripts ?) ,writing modules is someway bound to not polluting 
>>that namespace (really IMO).
> 
> 
> I'm afraid that I can't parse that sentence.

I show you a piece of code I need to define a function:

import string
all=string.maketrans('','')
badcars=all.translate(all,string.letters+string.digits)
table=string.maketrans(badcars,'_'*len(badcars))
def translate(text):
   return text.translate(table)

What I'm needing as a global (in globals() or at the module level or in 
the module namespace) is 'translate'.The rest of bindings (all,badcars 
and table) is something which is 'polluting' the module namespace.

Now this is the non polluting version :

class translate:
   import string
   all=string.maketrans('','')
   badcars=all.translate(all,string.letters+string.digits)
   @staticmethod
   def __call__(text,table=string.maketrans(badcars,'_'*len(badcars))):
 return text.translate(table)
translate=translate()

I'd like to have some help from the language in binding names this way.

Hope I've been clearer :)

Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-07-31 Thread Paolino
Steven D'Aprano wrote:

> def translate(text):
> import string
> all=string.maketrans('','')
> badcars=all.translate(all,string.letters+string.digits)
> table=string.maketrans(badcars,'_'*len(badcars))
> return text.translate(table)
> 
> No pollution.

And no efficience.Recalculating all,badcars and table was not an 
acceptable solution ,sorry if I didn't state this point :(

> Then after you are finished with the bindings, delete them:
> 
> import string
> all=string.maketrans('','')
> badcars=all.translate(all,string.letters+string.digits)
> table=string.maketrans(badcars,'_'*len(badcars))
> def translate(text):
> return text.translate(table)
> # clean up the temporary variables so as to prevent namespace pollution
> del string; del all; del badcars; del table

Well,a solution but not a programming pattern for an elegant language ?
More this is also loosing informations.

Probably I've not been clear with the word pollution and the example is 
poor.
I didn't mean 'binding to unuseful informations' but 'bindings  in a non 
-structured organization'

I restate the problem.Python is in some ways unable to project the 
module structure inside the module.Or ... namespace pattern instances 
seems  not deriving from a common pattern.

Finally, (before I get polemic which is not my aim) I start thinking 
classes (namespaces defined via 'class' keyword) are a specialization of 
generic namespaces in which there-defined methods get a special way of 
being called and __call__ method is a way of cloning access to them.
(Thin ice)

Don't really know if modules can be defined as specialization  of 
generic namespaces and be placed somewhere next to classes.

Even worse I get with methods and function namespaces.

Rob Williscroft wrote:

 > After 3 or 4 iterations I refactored you code to this:
 >
 > def translate( text )
 > import string
 > all=string.maketrans('','')
 > badcars=all.translate(all,string.letters+string.digits)
 > TABLE = string.maketrans(badcars,'_'*len(badcars))
 >
 > global translate
 > def translate( text ):
 > return text.translate(TABLE)
 >
 > return translate( text )

There is a way to access 'all' and 'badcars'  here?

In my trial translate.all and translate.badcars can be accessed easily 
and maybe coherently.

Thanks a lot, and don't tell me 'the dictator has marked the trail' ;)





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-07-31 Thread Paolino

>>Steven D'Aprano wrote:

> Why not? Is it too slow? Too many lines of code? Uses too much memory?
> What exactly is the problem? I would like to see your profile tests that
> show why this is not acceptable.

> Are you sure that this solution is less efficient than creating a class? A
> class has all that extra machinery and methods and attributes that needs
> to be created, only to be thrown away. How do you know that my solution is
> less efficient than your solution?

The example was an example , and my concern  is not about that example 
to be fast or small (readable probably), but for python programming 
tools as being complete, or academic interest or just to talk with 
people on a hot sunday (in this zone of the north emisphere) on 
interesting (for me at least) things.

The calculations for all,badcars and table are not complex in this case, 
so we can redo them often because we are wasters, but in other cases 
they can be different.

Me:
>>Even worse I get with methods and function namespaces.
> 
> What is "even worse" about them?
> 
For my thinking, worse is to understand how they derive their pattern 
from generic namespaces.
Methods seems not to have a writeble one,while functions as George and 
Rob remembered have one which is not read only.Why?

(Also my aim is to learn from postings not to show others' 
implementations are better or worse in the sense I prefer, times are 
gone for me for that. )

Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-07-31 Thread Paolino
George Sakkis wrote:

> Then write a closure. You get both encapsulation and efficience, and as
> a bonus, customization of the translating function:
> 
> import string
> 
> def translateFactory(validChars=string.letters+string.digits,
>  replaceChar='_'):
> all=string.maketrans('','')
> badcars=all.translate(all,validChars)
> table=string.maketrans(badcars, replaceChar*len(badcars))
> def translate(text):
> return text.translate(table)
> # bind any attributes you want to be accessible
> # translate.badcars = badcars
> # ...
> return translate
> 
> 
> tr = translateFactory()
> tr("Hel\xfflo")

This is clean,but I suppose it would get cumbersome if I want to have 
more functions in the namespace/factory and it implies all that bindings 
in the end.

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?

Thanks Paolino



___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-08-01 Thread Paolino
Bengt Richter wrote:



> Ok, to make the statement execute, execute function:
> 
>  >>> function()
>  >>> a=function.foo
>  >>> a
>  'something'
>  >>> vars(function)
>  {'foo': 'something'}
> 
Yep too stupid I've been :) Thanks







___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-08-01 Thread Paolino
George Sakkis wrote:
> Paolino wrote:
> 
> 
>>>>Even worse I get with methods and function namespaces.
>>>
>>>What is "even worse" about them?
>>>
>>
>>For my thinking, worse is to understand how they derive their pattern
>>from generic namespaces.
>>Methods seems not to have a writeble one,while functions as George and
>>Rob remembered have one which is not read only.Why?
> 
> 
> I'm not sure I can parse this successfully, let alone understand it.
> 

Functions' namespaces are writeble ,methods' not.

 >>> class C:
...   def m(self):pass
...   @classmethod
...   def cm(cls):pass
...   @staticmethod
...   def sm():pass
...
 >>> C.sm.set=None
 >>> C.cm.set=None
Traceback (most recent call last):
   File "", line 1, in ?
AttributeError: 'instancemethod' object has no attribute 'set'
# instancemethod? C.cm is a classmethod

 >>> C.m.set=None
Traceback (most recent call last):
   File "", line 1, in ?
AttributeError: 'instancemethod' object has no attribute 'set'
#
 >>>

Are these choices explained somewhere?

Isn't 'do more use of namespaces' a python zen-law?

Regards Paolino


___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-08-01 Thread Paolino
Paul Rubin wrote:
> Paolino <[EMAIL PROTECTED]> writes:
> 
>>What I'm needing as a global (in globals() or at the module level or
>>in the module namespace) is 'translate'.The rest of bindings
>>(all,badcars and table) is something which is 'polluting' the module
>>namespace.
> 
> 
> do you want
> __all__ = ['translate']
> ?
No I don't want to use another feature of the module namespace.
Well: good to know there is a hack in every corner.My point is now to 
understand similarities in python namespace types and why they present a 
different interface.

What I notice is the '.' operator is used to switch to an inside 
namespace ,until an attribute is found.Can I assume this is a rule?

Thanks anyway Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-08-01 Thread Paolino
Paolino wrote:


> Now this is the non polluting version :
> 
> class translate:
>import string
>all=string.maketrans('','')
>badcars=all.translate(all,string.letters+string.digits)
>@staticmethod
>def __call__(text,table=string.maketrans(badcars,'_'*len(badcars))):
>  return text.translate(table)
> translate=translate()
> 

## As now a good solution I got (from a RexFi hint in IRC) is via
## classmethods as it doesn't use free variables.
import string
class translate(object):

all=string.maketrans('','')
badcars=all.translate(all,string.letters+string.digits)
table=string.maketrans(badcars,'_'*len(badcars))
@classmethod
def translate(cls,text):
  return text.translate(cls.table)

translate=translate.translate

 Refactoring again this is the more elegant

import string

class translateUnderscore(object):
all=string.maketrans('','')
badcars=all.translate(all,string.letters+string.digits)
table=string.maketrans(badcars,'_'*len(badcars))
def __new__(cls,text):
  return text.translate(cls.table)

 Which allows for part-function reuse:

class translateQuestionmark(translate):
table=string.maketrans(translate.badcars,'?'*len(translate.badcars))

translateUnderscore('[EMAIL PROTECTED]')
translateQuestionmark('[EMAIL PROTECTED]')

###

An inefficency for these solutions is the further indirection to lookup 
attribute 'table' in the call (cls.table). (From RexFi also)



Regards Paolino


___ 
Aggiungi la toolbar di Yahoo! Search sul tuo Browser, e'gratis! 
http://it.toolbar.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doctest bug with nested triple quotes

2005-08-01 Thread Paolino
I can't reproduce the error. Freebsd,python 2.4 runs it.

 > cat x.py
"""
dummy = '''

something
here
'''
"""
import doctest; doctest.testmod()
 > python x.py
 >

maybe the file is different.
 > python -c "print open('x.py').read().encode('base64')"
IiIiCmR1bW15ID0gJycnCgpzb21ldGhpbmcKaGVyZQonJycKIiIiCmltcG9ydCBkb2N0ZXN0OyBk
b2N0ZXN0LnRlc3Rtb2QoKQo=

Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacement for keyword 'global' good idea? (e.g. 'modulescope' or 'module' better?)

2005-08-06 Thread Paolino
[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

I don't think the global keyword is useful actually.

What's so special in a module nemespace to be priviledged like that.

The point IMO is accessing names defined somewhere in the enclosing 
namespaces.

def enclosing():
   var=2
   def enclosed():
 outer var=4

this is the base of something useful.

as it is now you neeed

def enclosing():
   class Var:_=2
   def enclosed():
 Var._=4
or like others suggested

def enclosing():
   var=[]
   var[0]=2
   def enclosed():
 var[0]=4
which is like saying python is not working

It's ok to mark non locals,but why var=4 is not searched outside and 
var[0]=4 yes?

I think there is only one or none possible solution to an 'outer' 
statement which is the first bound name matching the 'outer' vars name 
in the chain of enclosing namespaces.

Why every instance doesn't point to its namespace and every namespace to 
its namespace? Unpythonic ?

Illogicities to my eyes or at least non-linerities that makes 'global' 
an interesting strangeness to talk about.

And that namespaces should start being easy sooner or later.


Regards Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacement for keyword 'global' good idea? (e.g. 'modulescope' or 'module' better?)

2005-08-06 Thread Paolino
Peter Hansen wrote:
> Paolino wrote:
> 
>>[EMAIL PROTECTED] wrote:
>>def enclosing():
>>  var=[]
>>  var[0]=2
>>  def enclosed():
>>var[0]=4
>>which is like saying python is not working
>>
>>It's ok to mark non locals,but why var=4 is not searched outside and 
>>var[0]=4 yes?
> 
> 
> Because "var=4" rebinds the name "var", while "var[0]=4" does not.  It's 
> exactly the same issue with using "global", where you don't need it if 
> you aren't rebinding the name.
> 
> (Those who don't understand the difference between "rebinding a name" 
> and "modifying an object" will need to figure out that distinction 
> before they can participate much in a discussion about Python scopes, I 
> think.)

The point is not to understand obvious technical things, but having a 
coherent programming framework.If I can modify an out of scope object 
(ie var list) without saying it's an 'outer' no problem as python looks 
for it, in fact I should put 'outer' to rebind var to 4 if I refer to 
'var' as an outer binding, python can find it if it exists, if it 
doesn't it can raise an error.

Many other ways to identify the scope layer of a binding can be thought 
about:having only 'global' and pretending that is the only useful 
namspace layer to be identify for changing its bindings is just a piece 
  of sense.

Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacement for keyword 'global' good idea? (e.g. 'modulescope'or 'module' better?)

2005-08-06 Thread Paolino
Terry Reedy wrote:
> "Paolino" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>[EMAIL PROTECTED] wrote:
>>I don't think the global keyword is useful actually.
>>What's so special in a module nemespace to be priviledged like that.
> 
> 
> The specialness of globals and locals was part of Python's original simple 
> namespace design, and is still reflected in exec statements and eval 
> functions, as well as in nested functions.
> 
> 
>>The point IMO is accessing names defined somewhere in the enclosing
>>namespaces.
> 
> 
> Accessing such names is already possible, even *after* the outer function 
> returns and the rest of its execution context is deleted.
> 
> 
>>def enclosing():
>>  var=2
>>  def enclosed():
>>outer var=4
> 
> 
> This is rebinding, rather than merely accessing.  Similar, but even more 
> problematical would be initial binding in outer from inner:
> 
> def enclosing():
> def enclosed():
> outer var = 4
> 
> 
>>this is the base of something useful.
> 
> 
> Actually, it is the reinvention of classes:
> 
> class enclosing(object):
> def __init__(self):
> self.var = 2
> def enclosed(self):
> self.var = 4
> 
This is using some really 'featured' namespace called class to do things 
which are useful to all namespaces.So not a solution but a hack.
Also 'self' is something really away from my example.A cloned namespace 
of the class probably.
Working hard with python namespaces is hacking: probably this makes us 
masters of python, when using namespaces should be a base knowledge.

> There was a long discussion on the pydev list a couple of years ago re 
> adding rebinding in addition to access (of outer variables).  I think, in 
> the end, Guido concluded that there was no compelling reason, as of then, 
> to add another general mechanism for private, sharable, rebindable 
> variables.
> 
> 
>>I think there is only one or none possible solution to an outer statement
> 
> 
> There were lots of proposals for both the exact syntax and semantics of 
> outer binding/rebinding.
> 
You cut the phrase and the meaning of it.

The only one solution I'm talking about is this:
  Stated 'outer var' in a namespace, jumping out of the namespace
  we found ourselves in another namespace.
  If 'var' is bound there, that's the solution to
  the 'outer' ,if not we jump out again.If the 'var' is never found we
  can raise an UnboundOuter error probably.


Regards Paolino


___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacement for keyword 'global' good idea? (e.g. 'modulescope'or 'module' better?)

2005-08-08 Thread Paolino
Bengt Richter wrote:

> Nor do we have any correspondence for bare names analogous to
> 
> setattr(obj, "name", value) <=> obj.name = value
> 
> e.g.,
> 
> setname(, "name", value)

Probably this parallelism is a better approach to what I commented 
before.Thanks for clarity.
> There is nowhere near the kind of control the programmer has over attribute 
> namespace
> use for bare-name use, even though by various means we are able to select 
> from a limited
> set of namespaces. (BTW, if  were a call to a suitable 
> builtin function
> that could return objects whose attribute namespace were the desired name 
> space, then setname
> could be effected with setattr, e.g.,
> 
> setattr(get_ns_obj(), "name", value)# name = value (defaulting to 
> local, same as get_ns_obj(0))
> setattr(get_ns_obj(1), "name", value)   # name = value (in lexically 
> immediately (1) enclosing scope)
> setattr(get_ns_obj(-1), "name", value)  # name = value (in global module 
> scope)
> )  
> 
Yes namespaces should be unified in their base behaviour.
> I am thinking that there is a subliminal discussion under a layer of red 
> herrings ;-)
> I refer to the subject of unification/generalizing/orthogonalizing by 
> removing special
> legacy restrictions (or not introducing special restrictions in a new 
> feature).
> 
> E.g., recently decorators were introduced, and part of the discussion (which 
> became explicit ;-)
> was whether to allow the expression following the '@' to be a fully general 
> expression, or
> whether to restrict it to names, dotted names, and function calls. The latter 
> won out.
> 
> Some regard this kind of restriction as paternalistic, and protest that "we 
> are adults here"
> (even though we are not all, and we others not all the time ;-)
> 
Uhmpf, adults==theorists and childrens==experimentals ?
> The BDFL has introduced many new ideas, yet has retained or introduced 
> restrictions on fully
> orthogonal functionality that might otherwise be allowed if e.g. names in 
> certain contexts
> were allowed to be full expressions. It goes the other way too. IIRC the list 
> of bases for
> a class will be allowed to be an empty "()" soon.
> 
> Bottom line, I think Python is eminently usable and very pleasant to use, but 
> I think bare name
> mechanisms could be improved.
> 
A good dose of humility could be good for reingeneering something ,if 
necessary.Python is very usable,and has an almost perfect surface layer.
But this is not enough.It needs to be strong and elegant in the insides 
  to survive.More, isn't the "Namespaces do more of them" a Python Zen Law ?

Thanks again for putting things in a saner and more open way then I did.

Regards Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


namespaces

2005-08-09 Thread Paolino
Why descriptor mechanism doesn't apply to modules?

I suspect another anomaly in the namespaces implementations.
class Mosse(object):
   def __get__(self,*_):
 print 'HERE'

m=Mosse()
m # doesn't work

import new
mod=new.module('hopeless')
mod.m=Mosse()
assert 'm' in mod.__dict__ # this is said to be the key for descriptors
# to be called
mod.m # doesn't work



Thanks Paolino


___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-08-09 Thread Paolino
Peter Otten wrote:
> Paolino wrote:
> 
> 
>>Why descriptor mechanism doesn't apply to modules?
> 
> 
> Because modules are instances of the module class and the descriptor has to
> be defined in the class in order to work with the instance. E. g.:
> 
> 
Got it,thanks.
Then there is no way of having descriptors at module level,as 'module' 
class is not updatable.





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-08-10 Thread Paolino
Scott David Daniels wrote:

> Well, an entry in the dictionary "sys.modules" is what is returned by
> imports, so you could either pre-replace or post-replace a module by
> an object which uses the descriptor technique to get to some (but not
> necessarily all) of the attributes.  Think of this technique as a
> hack to get to a goal, rather than a good technique to use; good for
> debugging, not so nice for production work.  If you still don't know
> how to do this from this admittedly sketchy description, I'd suggest
> you avoid trying it altogether.
> 
Thanks.Is don't know if this is *the* way to wrap the module ?

import new,sys
class Free(new.module):
   def __init__(self,moduleName):
 new.module.__init__(self,moduleName)
 assert moduleName in sys.modules
 self.__dict__.update(sys.modules[moduleName].__dict__)
 sys.modules[moduleName]=self
   def desc(self):
 pass



Free(__name__) #'no errors'


but 'desc' is not defined in this namespace.

Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces

2005-08-10 Thread Paolino
Bengt Richter wrote:


> Another thought/bf would be a way to extend the attribute namespace of an 
> arbitrary object
> by chaining the attribute name spaces of a sequence of objects (this would be 
> a language mod)
> e.g., (sort of a dynamic instance attribute mixin)
> 
>  obj ..= a, b, c  # a sequence of objects
> 
> then
> 
>  obj.x  # looks for obj.x, then a.x then b.x then c.x before giving up 
> with attribute error
>  obj ..=()  # clears chained attribute name space ?
> 

Something like a __lookup__ attribute for all instances which are 
namespaces.
Are all objects namespaces or have all objects a namespace?

Also syntax:
  lookup(obj).append(x)

I suppose bound methods will not be found,but in that case some tolerant 
unbound methods could do,naturally if the PEP on eliminating them will 
be accepted.That check they do on the first parameter they push in the 
function (aka 'self')  is really contrasting dinamycal Python IMO.

> Then you could add a property to the namespace of a module by adding an 
> object whose class defines
> the property, like
> 
>  mod ..= objhavingproperty # same tuple ambiguity as with 'somestr' % x
> 
> something analogous to += on immutables would have to be done for builtin 
> objects I suppose.
This is a little hard for me.Has it something to do with extensions also?

Regards Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is this?

2005-08-10 Thread Paolino
Jiri Barton wrote:
> Hi everyone,
> 
> I have a problem with initialization.
> 
>>>>a, b = [[]]*2
>>>>a.append(1)
>>>>b
> [1]
> 
> Why is this? Why does not this behave like the below:
> 
 >>> a, b = [[]]*2
 >>> a==b
True
> 

> And, just to add to my confusion:
> 
> 
>>>>[[]]*2
> 
> [[], []]
> 
>>>>[[], []] == [[]]*2
> 
> True
This confuses me also,looks like empty lists share same object.

Paolino






___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is this?

2005-08-10 Thread Paolino
Paolino wrote:
> Jiri Barton wrote:
> 
>>Hi everyone,
>>
>>I have a problem with initialization.
>>
>>
>>>>>a, b = [[]]*2
>>>>>a.append(1)
>>>>>b
>>
>>[1]
>>
>>Why is this? Why does not this behave like the below:
>>
> 
>  >>> a, b = [[]]*2
>  >>> a==b
> True
Ooops I should write 'a is b'
> 
> 
>>And, just to add to my confusion:
>>
>>
>>
>>>>>[[]]*2
>>
>>[[], []]
>>
>>
>>>>>[[], []] == [[]]*2
>>
>>True
> 
> This confuses me also,looks like empty lists share same object.
This is actually OK as lists are compared for their contents ;-)

> Paolino
> 
> 
>   
> 
>   
>   
> ___ 
> Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
> http://mail.yahoo.it


___ 
Aggiungi la toolbar di Yahoo! Search sul tuo Browser, e'gratis! 
http://it.toolbar.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


help in algorithm

2005-08-10 Thread Paolino
I have  a self organizing net which aim is clustering words.
Let's think the clustering is about their 2-grams set.
Words then are instances of this class.

class clusterable(str):
   def __abs__(self):# the set of q-grams (to be calculated only once)
 return set([(self+self[0])[n:n+2] for n in range(len(self))])
   def __sub__(self,other): # the q-grams distance between 2 words
 set1=abs(self)
 set2=abs(other)
 return len(set1|set2)-len(set1&set2)

I'm looking  for the medium  of a set of words, as the word  which 
minimizes the sum of the distances from those words.

Aka:sum([medium-word for word in words])


Thanks for ideas, Paolino







___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


set of sets

2005-08-11 Thread Paolino
I thought rewriting __hash__ should be enough to avoid mutables problem but:

class H(set):
   def __hash__(self)
 return id(self)

s=H()

f=set()

f.add(s)
f.remove(s)

the add succeeds
the remove fails eventually not calling hash(s).


Thanks for help

Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: set of sets

2005-08-11 Thread Paolino
Matteo Dell'Amico wrote:
> Paolino wrote:
> 
>>I thought rewriting __hash__ should be enough to avoid mutables problem 
>>but:
>>
>>class H(set):
>>  def __hash__(self)
>>return id(self)
>>
>>s=H()
>>
>>f=set()
>>
>>f.add(s)
>>f.remove(s)
>>
>>the add succeeds
>>the remove fails eventually not calling hash(s).
> 
> 
> Why don't you just use "frozenset"?
> 
This is what I'm doing, but the problem remains IMO.
Anyway with frozenset I have to override __new__ instead of __init__ to 
make the initialization which is an operation not described in the 
frozenset  docs, which  makes subclassing frozenset a different operation.

Thanks Paolino


___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help in algorithm

2005-08-11 Thread Paolino
Bengt Richter wrote:
> On Wed, 10 Aug 2005 16:51:55 +0200, Paolino <[EMAIL PROTECTED]> wrote:
> 
> 
>>I have  a self organizing net which aim is clustering words.
>>Let's think the clustering is about their 2-grams set.
>>Words then are instances of this class.
>>
>>class clusterable(str):
>>  def __abs__(self):# the set of q-grams (to be calculated only once)
>>return set([(self+self[0])[n:n+2] for n in range(len(self))])
>>  def __sub__(self,other): # the q-grams distance between 2 words
>>set1=abs(self)
>>set2=abs(other)
>>return len(set1|set2)-len(set1&set2)
>>
>>I'm looking  for the medium  of a set of words, as the word  which 
>>minimizes the sum of the distances from those words.
>>
>>Aka:sum([medium-word for word in words])
>>
>>
>>Thanks for ideas, Paolino
>>
> 
> Just wondering if this is a desired result:
> 
>  >>> clusterable('banana')-clusterable('bananana')
>  0

Yes, the clustering is the main filter,it's good (I hope) to cut the 
space of words down one or two magnitudes.
Final choices must be done with the expensive Levenstain distance, or 
other edit-type distance.

Now I'm using an empirical solution where I suppose the best set has 
lenght L equal the medium of the lenghts.Then I choose from the 
frequency distribution of 2-grams the first L 2-grams.

I have no clue this is the right set and I'm sure that set is not a word 
as there is no chance to chain those 2-grams to form a word.

Thanks for comments

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


Re: How to Adding Functionality to a Class by metaclass(not by inherit)

2005-08-12 Thread Paolino
Dont' know where are you going with that but if what you need is 
cancelling some attributes when inheriting then probably this is a 
cleaner approach:

class Meta(type):
   def __init__(cls, name, bases, dic):
 def attributeError(*_):
   raise AttributeError
 for base in bases:
   for dont in base.privates:
 setattr(cls,dont,attributeError) #override private methods

class Foo(object):
   privates=('f',)
   def f(self):
 pass
   def g(self):
 pass

class Bar(Foo):
   __metaclass__ = Meta

b=Bar()
b.g()
b.f()

and it implies writing only one metaclass.






___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __getattribute__ for class object

2005-08-12 Thread Paolino
Sylvain Ferriol wrote:
> hello
> when i define __getattribute__ in a class, it is for the class instances
> but if i want to have a __getattribute__ for class attributes
> 
> how can i do that ?
> 

Skating on thin ice eh.Read something on metaclasses.


class Meta(type):
   def __getattribute__(klass,attr):
 value=type.__getattribute__(klass,attr)
 print attr,'==',value
 return value

class Foo(object):
   __metaclass__=Meta
   a=2

Foo.a

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


Re: simpli int/str problem

2005-08-12 Thread Paolino
sinan . wrote:
> hi all,
> i have a string and int values in same dictionary like this
> dict = {'str_name': 'etc' , 'int_name' : 112 }
> the error occures when do this
> SQL = "INSERT INTO (`AH`, `BH` ) VALUES ('" + dict['str_name'] + "',
> '" + dict['int_name'] + "')"
> cursor.execute(SQL)
> python does not accep dict['int_name'] in SQL variable but when i
> convert this variable to the str , python accepts but i cannot insert
> that into database because database only accept int in `BH `
> thanks.
Try use:
SQL = "INSERT INTO (`AH`, `BH` ) VALUES 
('%s,%d)"%(dict['str_name'],dict['int_name'])

Paolino


___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug on Python2.3.4 [FreeBSD]?

2005-08-12 Thread paolino
Uwe Mayer wrote:
> 
> 
> Hi,
> 
> AFAICT there seems to be a bug on FreeBSD's Python 2.3.4 open function. The
> documentation states:
> 
> 
>>Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+'
>>truncates the file). Append 'b' to the mode to open the file in binary
>>mode, on systems that differentiate between binary and text files (else it
>>is ignored). If the file cannot be opened, IOError is raised.   
> 
> 
> Consider:
> 
> $ cat test
> lalala
> 
> $ python2.3
> Python 2.3.4 (#2, Jan  4 2005, 04:42:43)
> [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4
> Type "help", "copyright", "credits" or "license" for more information.
> 
f = open('test', 'r+')
f.read()
> 
> 'lalala\n'
> 
f.write('testing')
f.close()

> 
> [1]+  Stopped python2.3
> $ cat test
> lalala
> 
> -> write did not work; ok
> 

This worked here on freebsd 5.4 / python 2.4

> $ fg
> python2.3
> 
f = open('test', 'a+')
f.read()
> 
> ''
> 
> -> append mode does not read from file, *not ok*
> 
> 
This is right IMO 'a' is appending so seek(-1)


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


Re: catching all exceptions

2005-08-13 Thread Paolino
[EMAIL PROTECTED] wrote:
> Hello,
> 
> I'd like to catch all exeptions and be able to inspect them.
> 
> The simple case: I know which exceptions I'll get:
> 
> # standard textbook example:
> try:
> something()
> except ThisException, e:
> print "some error occurred: ", str(e)
> 
> 
> The not-so-simple case: Handling all other exceptions:
> 
> # nice-to-have:
> try:
> something()
> except *, e:
> print "some error occurred: ", type(e), str(e)
> 
> 
except Exception:# catch them all.

Then use moudule 'traceback' to inspect

Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


A (unpythonic) pythonable mixin recipe.

2005-08-16 Thread Paolino
I had always been negative on the boldeness of python on insisting that 
unbound methods should have been applied only to its im_class instances.
Anyway this time I mixed in rightly, so I post this for comments.

## looking for a discovery .Start #

class _Mixin(object):
   def __init__(self,main,instance,*args,**kwargs):
  # do mixin businnes
  main.__reinit__(self,instance) # the caveated interface
  # probably missing __reinit__ in main
  # one could assume main.__init__ should do
   def mixinMethod(self):
 print 'mixinMethod on',repr(self)

def Mixin(instance,*args,**kwargs):
   klass=instance.__class__
   return type('Mix+%s'%klass.__name__,(_Mixin,klass),{})(klass,instance)

 end of hot water discovery ##

class Base(object):
   def __reinit__(self,another):
 # do something so that self is like another (painful in general)
 # easy for mutables, impossible for other
 pass

b=Base()
b=Mixin(b)

assert isinstance(b,Base)
b.mixinMethod() # doesn't fail with absurds

 The next doesn't work 
# l=[1,2,3]
# l.__reinit__=l.__init__  # exception IMAConservativeLanguage

class L(list):
   __reinit__=lambda self,other:list.__init__(self,other)

l=L([1,2,3])
l=Mixin(l)
l.mixinMethod()

Regards Paolino







___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2005-08-16 Thread Paolino
Rocco Moretti wrote:
> Cameron Laird wrote:
> 
>> Andy Smith rails against "frameworks":
>> 
>> http://an9.org/devdev/why_frameworks_suck?sxip-homesite=&checked=1  
> 
> 
> Slapdash Summary: Libraries good, frameworks bad - they are a 
> straightjackets and limit sharing.
> 
> Which lead me to the question - what's the difference between a library 
> and a framework?

A library is a set of base behaviours you have to learn separetly and 
deeply to inherit a mix of them and build an aspect of your program.
A framework is a dumb runnable program in which you must insert your 
plugins as specifications to drive it towards a useful instance of it.

A framework misses libraries of methods to become useful.


A library is a set of loosely coupled classes useful for machines to 
attack a problem .
A framework is a set of highly coupled interfaces useful for humans to 
describe a task.

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


An observer pattern application.

2005-08-18 Thread Paolino
Lately I was needing to use multiple inheritance to split behaviour of a 
class and modularize it.
But the problem raises when the need is to add operations to a method 
already present in one of them from another.
I think the technical solution is the use of 'super'.
Then I tried to write a decorator for automatize the 'super' call,but I 
failed.

Next solution is implementing the observer pattern on methods call.
I'm pretty sure there are bugs and ideas to be corrected in the next 
code,any help and comment appreciated.

Regards Paolino



''' A module collecting classes for known patterns

 '''

import types

class Observer(dict):
   ''' A class defining some decorators for function/methods to 
chain/link them when called .To do:implement pre event execution hooking'''

   def __call__(self,observed,args,kwargs):
 for reaction in self.get(observed,()):
   reaction(*args,**kwargs)

   def emit(self,method,observed=None):
 ''' A decorator for functions to signal their calling.Post hook 
cablated'''
 def wrapper(*args,**kwargs):
   if  observed:
 if type(observed) is types.MethodType:
   event=observed.im_func
 else:
   event=observed
   else:
 event=wrapper
   result=method(*args,**kwargs)
   self(wrapper,args,kwargs)
   return result
 return  wrapper

   def emitOther(self,observed):
 ''' A decorator facility to let the function/method emit another 
event (not itself)'''
 def wrapEmit(method):
   return self.emit(method,observed)
 return wrapEmit

   def reactOn(self,*observeds):
 ''' a decorator to set the function/method as a reaction to 
*observeds event.
 Remember to use __ name mangling when working on methods to be 
able to use
 same reaction name on multiple class inheritances'''
 def reaction(method):
   for observed in observeds:
 if type(observed) is types.MethodType:
   observed=observed.im_func
 self.setdefault(observed,set()).add(method)
   return method
 return reaction


if __name__=='__main__':
   observer=Observer()
   class base(object):
 @observer.emit
 def method(self,*args,**kwargs):
   print '%s.method'%str(self),args,kwargs

   class extensionA(object):
 @observer.reactOn(base.method)
 def __methodReaction(self,*args,**kwargs):
   print 'A,%s.methodReaction'%str(self),args,kwargs

   class extensionB(object):
 @observer.reactOn(base.method)
 def __methodReaction(self,*args,**kwargs):
   print 'B,%s.methodReaction'%str(self),args,kwargs

   class applicable(base,extensionA,extensionB):
 @observer.reactOn(base.method)
 def __methodReaction(self,*args,**kwargs):
   print 'applicable,%s.methodReaction'%str(self),args,kwargs

 pass

   applicable().method('cucu')


___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict duplicity

2005-08-18 Thread Paolino
Randy Bush wrote:
> a dict written as
> 
>pKey = (prefix, pLen, origin)
> 
>val = dict.get(pKey)
>if val == None:
>   dict[pKey] = (timeB, timeB)
>else:
>   if val[0] > timeB:  val[0] = timeB
>   if val[1] < timeB:  val[1] = timeB
>   dict[pKey] = val
> 
> and read back as
> 
>for pKey, pVal in dict.iteritems():
>   print \
>  pKey[0], hash(pKey[0]), \
>  pKey[1], hash(pKey[1]), \
>  pKey[2], hash(pKey[2]), \
>  "hash=", hash(pKey), \
>  pVal[0], hash(pVal[0]), \
>  pVal[1], hash(pVal[1])
> 
> when run with | sort, produces
> 
> 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000 
> 917088000 917088000
> 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000 
> 917088000 917088000
> 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000 
> 917088000 917088000
> 12.0.0.0 -2054516913 8 8 7018 329707286 hash= -604503432 917088000 917088000 
> 917088000 917088000
> 12.0.0.0 -2054516913 9 -1293912648 7018 329707286 hash= -1578430040 917088000 
> 917088000 917088000 917088000
> 12.0.0.0 -2054516913 9 -1293912648 7018 329707286 hash= -1578430040 917088000 
> 917088000 917088000 917088000
> 
> not that there are two entries with the same hash=
> 
> i am utterly confused
> 
> randy
> 
I'm not sure I got your question but having the same hash(key) is not 
having the same key for a dict.

 >>> {-1:0,-2:0}
{-2: 0, -1: 0}
 >>> hash(-1)!=hash(-2)
False

A key lookup in a dict involve real keys comparisons via '==' among the 
keys of the bin identified by the hash of the key.


Regard Paolino


___ 
Yahoo! Messenger: chiamate gratuite in tutto il mondo 
http://it.beta.messenger.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a unique id for bound methods?

2005-08-19 Thread Paolino
Russell E. Owen wrote:

> The "hash" function looks promising -- it prints out consistent values 
> if I use it instead of "id" in the code above. Is it stable and unique? 
> The documentation talks about "objects" again, which given the behavior 
> of id makes me pretty nervous.
> 
I dont know how the hash of a bound method is calculated,but as the 
function of the method is a stable and referenced object and as 
instances lives are in your hands,then an id(self)^id(self.meth.im_func) 
should be a chance for that 'hash' function.

def methodId(boundMethod):
   return id(boundMethod.im_self)^id(boundMethod.im_func)

class cls(object):
   def __init__(self):
 print methodId(self.meth1)
 print methodId(self.meth2)
   def meth1(self):
 pass
   def meth2(self):
 pass

c = cls()
print methodId(c.meth1)
print methodId(c.meth2)

I think this is giving what you expected.

Regards Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: algorithm for non-dimensionalization

2005-08-26 Thread Paolino
[EMAIL PROTECTED] wrote:
> Hi,
> I am trying to non-dimensionalize some data I have obtained. There are
> no 'standard' dimensionless groups for my application, so I would like
> to obtain the 'best' non-dimensional groups based on some statistical
> measures of the resulting transformed data.
> 
> At this point, I am looking for a way to generate dimensionless
> groupings from a set of base units. I would like to have a way to
> output all dimensionless groups that comprise no more than some
> specified number of fundamental (or base) units.
> 
> For instance, if I have data like the following:
> 
> dat1(length), dat2(time), dat3(length), dat4(length/time),
> dat5(length^2)
> 
> and I want dimensionless groups with no more than four base units, I
> would like a result like the following:
> 
> dat1/dat3, dat1/(dat2*dat4), dat5/(dat1*dat3), dat5/(dat2*dat4*dat1),
> ...
> 
> I plan to code this in Python, and would appreciate any thoughts you
> might have about algorithms or approaches to carry out this task.
> 
> Thank you.
> 
> -g
> 
Thinking more,it's an eigenvector problem.

Where all dat* magnitudes are expressed as a vector of integers in the 
dimensions space,and the result vector is all 0.

IE
E=[m][L^2][T^-2]
v=[L][T^-1]
f=[T^-1]
p=[m][L][T^-1]
..


in the mass,lenght,time space are

[1,2,-2]
[0,1,-1]
[0,0,-1]
[1,1,-1]

say matrix D

then

D*[x1,x2,x3,x4]=[0,0,0] (looking for adimensionals)

So you are looking for an eigenvector formed by only integers.



Ciao Paolino







___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add lists to class?

2005-09-02 Thread Paolino
Mike Meyer wrote:
> "BBands" <[EMAIL PROTECTED]> writes:
> 
> 
>>I have a list with some strings in in it, 'one', 'two' 'three' and so
>>on. I would like to add lists to a class with those names. I have no
>>way of knowing what will be in the list or how long the list will be in
>>advance.
> 
> 
> Others have told you how to do it. Now I'm going to tell you why you
> shouldn't.
> 
> First, since you don't know the names of the attributes you added, you
> can't possibly write code that references them in the normal way. So
> is there really much point in making them an attribute at all?
> 
> Second, since you don't know the names of the attributes you added,
> you don't know if one of more of them is going to clobber a feafure of
> the class that you want to use for something else. I.e., consider:
> 
> 
>>>>class C:
> 
> ...  pass
> ... 
> 
>>>>c = C()
>>>>print c
> 
> <__main__.C instance at 0x8270b4c>
> 
>>>>c.__str__ = 'foo'
>>>>print c
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: 'str' object is not callable
> 
> 
> I.e. - if someone adds a __str__ attribute to your class, you won't be
> able to print it any more. Not a good thing.
> 
> In general, you probably want a dictionary instead of attributes:
> 
> 
>>>>class C(dict):
> 
> ...  def __init__(self, l):
> ...   for i in l:
> ...self[i] = []
> ... 
> 
>>>>c = C(['a', 'b', 'c'])
>>>>c['a']
> 
> []
> 
and 2c more to use attributes but prevent overriding of real attributes

def __getattr__(self,name):
  if name in self:
return self[name]
  raise AttributeError

Paolino





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


AttributeError of a module instance

2004-12-26 Thread Paolino
I'd like to catch AttributeError on the module level,so that  I can 
declare default bindings for useds defore definition.How is this  to be 
done?Thanks for help.
Paolino

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


Re: AttributeError of a module instance

2004-12-27 Thread Paolino
Terry Reedy wrote:

I'd like to catch AttributeError on the module level,so that  I can
declare default bindings for useds defore definition.How is this  to 
be done?

'defore' is obviously 'before', but what is 'useds'?  In and case...
Unresolved bindings,possibly like
>>> _rdf_type
Traceback (most recent call last):
 File "", line 1, in ?
NameError: name '_rdf_type' is not defined
If you are asking for the module equivalent of __getattr__ class 
methods, there is none.  Modules are namespaces.  They are like dicts 
but minus the dict methods and with .attribute instead of 
['attribute'] access.  This is possible because all 'keys' are names 
(hence 'namespace').
In the previous example I'd like to see an answer like
''
even if I never defined it.Is this not possible?I use __getattr__ in 
other situations,and it's very useful for proxying procedures,I was 
hoping on a real objectivation of a module.
Why the language should not consider a module as a 'normal' instance 
with 'normal' attributes?

Sorry for my language skills.Paolino
--
http://mail.python.org/mailman/listinfo/python-list