[Tutor] Writing Python Script to read battery level

2011-01-17 Thread FT

Allan,

Is there a way to read the battery level using Python?

I am totally blind and want to write a script to capture the battery level 
and send it through the voice activeX so I can speak it...

Bruce

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Writing Python Script to read battery level

2011-01-17 Thread ALAN GAULD
> Is there a way to read the battery level using  Python?

> 
> I am totally blind and want to write a script to  capture 
> the battery level and send it through the voice activeX so I can speak  it...

An interesting project. Unfortunately I don't know enough 
about how PCs do that kind of low level monitoring. Given that Windows 
displays the battery level in the system tray I'm assuming there will 
be a Windows API Call that can do it. If thats the case then yes you 
should be able to do that from Python via Pythonwin or ctypes.
You will need to do some searching of the Microsoft documentation.
I'd start with the MDSN web site...

It will probably take a bit of experimentation to get right but Pytthon 
is good for doing that kind of work using the interactive prompt.

Somebody else might have a more specific answer.

Alan G.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Writing Python Script to read battery level

2011-01-17 Thread Tim Golden

On 17/01/2011 03:01, FT wrote:

Is there a way to read the battery level using Python?

I am totally blind and want to write a script to capture the battery
level and send it through the voice activeX so I can speak it...


WMI should be able to query the battery information:


import wmi

c = wmi.WMI ()
for battery in c.Win32_Battery ():
  print battery.Caption, battery.EstimatedChargeRemaining



The pure-python wmi module is based here:

  http://timgolden.me.uk/python/wmi/index.html

and can be installed via easy_install / pip.

Information on the attributes of the Win32_Battery class are
available here:

  http://msdn.microsoft.com/en-us/library/aa394074%28v=vs.85%29.aspx


You might also be interested in the pyttsx project
(successor to the Windows-specific pytts):

  http://pypi.python.org/pypi/pyttsx/1.0

although if you have existing code to work with an ActiveX
control then I doubt it brings you any advantages.

TJG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Writing Python Script to read battery level

2011-01-17 Thread python
FT,

> Is there a way to read the battery level using Python?

Check out the following code snippet:

Get info on power/battery status
http://nullege.com/codes/show/src@jaraco.windows-1.6@jaraco@wind...@power.py/14/ctypes.wintypes.BOOL

This code snippet requires the following 3rd party packages:

1. Mark Hammond's pywin32 (comes bundled with ActiveState versions of
Python)
https://sourceforge.net/projects/pywin32/

2. Tim Golden's wmi (requires pywin32)
http://timgolden.me.uk/python/wmi.html 

There's also a Python mailing list dedicated to Windows API questions:
http://mail.python.org/mailman/listinfo/python-win32

Good luck!

Malcolm
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about manipulate images!

2011-01-17 Thread Elwin Estle


--- On Sun, 1/16/11, zhengqing gan  wrote:

> From: zhengqing gan 
> Subject: [Tutor] question about manipulate images!
> To: tutor@python.org
> Date: Sunday, January 16, 2011, 11:37 PM
> Hi, All:
>      I have a question about
> manipulating images.
>      If I have a image, is there a kind
> of algorithm to convert it
> into kind of Iphone icon style? part transparent,
> gradient
>      Thanks!

You might be better off using a program like Photoshop, The Gimp, or perhaps 
even Inkscape for this.


  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about manipulate images!

2011-01-17 Thread Alan Gauld

"zhengqing gan"  wrote

I have a question about manipulating images.


In Python that usually translates to use PIL...


If I have a image, is there a kind of algorithm to convert it
into kind of Iphone icon style? part transparent, gradient


PIL can do most of that but you will need to understand 
exactly which transformations you need to apply which will 
require some background research on your part.


wikipedia is always a good starting point.

HTH

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Refcount in C extensions

2011-01-17 Thread Izz ad-Din Ruhulessin
Hi Steve,

Your remarks about Cython pushed me over the edge into the Unknown, this
weekend I decided to download it and check it out.

I've been using it the past few days and it totally rocks. It really feels
like I was chained before and now I'm not; like where some simple Python
operations could require tens or even hundreds of lines of code, Cython make
life easiër. A real life-saver, thanks!

I also like how simple it is to import C functions to python, btw.

Kind regards,

Izz ad-Din

2011/1/14 Stefan Behnel 

> Izz ad-Din Ruhulessin, 14.01.2011 19:49:
>
>  Thanks for your quick reply and clearing the issue up for me. Using your
>> answer, I rewrote the function to this:
>>
>> double Py_GetAttr_DoubleFromFloat(PyObject *obj, const char *attr)
>>
>>>
>>> {
>>>
>>> PyObject *get_attr, *py_float;
>>>
>>> int has_attr;
>>>
>>>
>>>  //Check if the given object has the given attribute.

>>>
>>> has_attr = PyObject_HasAttrString(obj, attr);
>>>
>>> if (has_attr == False) {
>>>
>>> return -.0;
>>>
>>> }
>>>
>>>
>>>  //Get our attribute and convert it to a double.

>>>
>>> get_attr = PyObject_GetAttrString(obj, attr);
>>>
>>
> Note that HasAttr() calls GetAttr() internally, so it's actually faster to
> call GetAttr() and check for an exception (and clear it). That's basically
> how HasAttr() works, except that it doesn't tell you the result if the
> attribute existed.
>
>
>
>  py_float = PyNumber_Float(get_attr);
>>>
>>> if (py_float == NULL) {
>>>
>>> Py_DECREF(get_attr);
>>>
>>> Py_XDECREF(py_float);
>>>
>>
> You already know that py_float is NULL, so Py_XDECREF() is a no-op.
>
>
>
>  return -.0;
>>>
>>> }
>>>
>>> double output = PyFloat_AsDouble(py_float);
>>>
>>>
>>>  //Garbage collect

>>>
>>> Py_DECREF(get_attr);
>>>
>>> Py_XDECREF(py_float);
>>>
>>
> py_float cannot be NULL at this point, so the Py_XDECREF() will compile
> into Py_DECREF().
>
>
>  (False is 0)
>>
>
> In that case, better write 0 instead.
>
>
>
>  Regarding your Cython suggestion, as a matter of coincidence I have been
>> reading about it in the past few days. I'm in doubt of using it however,
>> because I have a lot of native C code that would require rewriting if I
>> switched to Cython.
>>
>
> No need for that, Cython can call external C code natively. So you can make
> the switch step by step.
>
>
>
>  On the other hand, your example shows that such a
>> one-time rewrite will pay-off big time in future development speed.
>>
>
> It usually does, yes. It often even pays off immediately because a rewrite
> tends to be pretty straight forward (basically, read and understand the C
> code, rip out all low-level stuff and replace the rest with simpler code),
> and while doing so, some bugs tend to disappear, the code becomes simpler,
> safer and often also faster, and new features appear while you're at it.
>
>
> Stefan
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about manipulate images!

2011-01-17 Thread zhengqing gan
Hi,
   Thanks for the reply.
   But I found that there are some website which can convert images
into iphone icon style images, there should be an kind of algorithm to
manipulate.
   Thanks!


On Mon, Jan 17, 2011 at 3:33 AM, Elwin Estle  wrote:
>
>
> --- On Sun, 1/16/11, zhengqing gan  wrote:
>
>> From: zhengqing gan 
>> Subject: [Tutor] question about manipulate images!
>> To: tutor@python.org
>> Date: Sunday, January 16, 2011, 11:37 PM
>> Hi, All:
>>      I have a question about
>> manipulating images.
>>      If I have a image, is there a kind
>> of algorithm to convert it
>> into kind of Iphone icon style? part transparent,
>> gradient
>>      Thanks!
>
> You might be better off using a program like Photoshop, The Gimp, or perhaps 
> even Inkscape for this.
>
>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about manipulate images!

2011-01-17 Thread Eduardo Vieira
Hi. Try to find a tutorial on the steps to achieve such effect in a graphic
program. Then map it to the scrpting steps to do the same with pil, python
for gimp, for inkscape or simply Imagemagick.

On 2011-01-17 8:37 AM, "zhengqing gan"  wrote:

Hi,
  Thanks for the reply.
  But I found that there are some website which can convert images
into iphone icon style images, there should be an kind of algorithm to
manipulate.
  Thanks!



On Mon, Jan 17, 2011 at 3:33 AM, Elwin Estle 
wrote:
>
>
> --- On Sun,...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Writing Python Script to read battery level

2011-01-17 Thread Bill Allen
Tim,

Thanks for posting this.   I have several uses for this WMI module at my
work.


--Bill






On Mon, Jan 17, 2011 at 04:07, Tim Golden  wrote:

> On 17/01/2011 03:01, FT wrote:
>
>> Is there a way to read the battery level using Python?
>>
>> I am totally blind and want to write a script to capture the battery
>> level and send it through the voice activeX so I can speak it...
>>
>
> WMI should be able to query the battery information:
>
> 
> import wmi
>
> c = wmi.WMI ()
> for battery in c.Win32_Battery ():
>  print battery.Caption, battery.EstimatedChargeRemaining
>
> 
>
> The pure-python wmi module is based here:
>
>  http://timgolden.me.uk/python/wmi/index.html
>
> and can be installed via easy_install / pip.
>
> Information on the attributes of the Win32_Battery class are
> available here:
>
>  http://msdn.microsoft.com/en-us/library/aa394074%28v=vs.85%29.aspx
>
>
> You might also be interested in the pyttsx project
> (successor to the Windows-specific pytts):
>
>  http://pypi.python.org/pypi/pyttsx/1.0
>
> although if you have existing code to work with an ActiveX
> control then I doubt it brings you any advantages.
>
> TJG
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Writing Python Script to read battery level

2011-01-17 Thread Tim Golden

On 17/01/2011 18:35, Bill Allen wrote:

Tim,

Thanks for posting this.   I have several uses for this WMI module at
my work.


Glad it's useful...

TJG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about manipulate images!

2011-01-17 Thread Corey Richardson
On 01/17/2011 10:34 AM, zhengqing gan wrote:
> Hi,
>Thanks for the reply.
>But I found that there are some website which can convert images
> into iphone icon style images, there should be an kind of algorithm to
> manipulate.
>Thanks!
> 
> 

>From playing with
http://wizardtoolkit.com/shooter/iPhone-Icon-Generator, it appears all
that needs to be done is add a semi- or completely-transparent ovalish
blob on the top, and possibly a metallic looking frame. While I'm sure
you could take the (probably) tens to hundreds of hours finding a
mathematical formula to define that, you can probably just whip up some
semi-transparent blobs in GIMP/Photoshop/what-have-you and a metallic
frame. Then you can use PIL to combine them. Try:
http://python-forum.com/pythonforum/viewtopic.php?f=3&t=3462&start=0
http://stackoverflow.com/questions/3374878/with-the-python-imaging-library-pil-how-does-one-compose-an-image-with-an-alph

~Corey
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Exactly duplicating strftime behavior?

2011-01-17 Thread Izz ad-Din Ruhulessin
Hi all,

I'm designing a module which aims to provide full compatibility with
Pythons' datetime module.

However, I can't find out how some operators in strftime function, namely:
those who use the locale. (%a, %A, %b, etc.)

How do I access this locale and it's values?

Thanks in advance.

Kind regards,

Izz ad-Din
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] What is __weakref__ ?

2011-01-17 Thread Karim


Hello,

I am wondering what is this special class attribut. I know __dict__, 
slots. I use slots = [] when I want to use a read only class.

But is anyone could explain with a little example the use of __weakref__?

Regards
karim
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Why super does not work !

2011-01-17 Thread Karim



Hello,

I implemented Observer DP on a listbox (Tkinter) as follows and I don't 
understand why super() is not working and Observable.__init__(self) is 
working, cf below:


class ListObservable(Listbox, Observable):
"""Creation de widget Listbox"""
def __init__(self):
super(ListObservable, self).__init__()
#Observable.__init__(self)
self._value = None
self.listeContenu = StringVar()
self.listeContenu.set(' '.join(sorted(data_base.keys(
self.liste = Listbox(listvariable=self.listeContenu, 
selectmode='single')

self.liste.grid(row=0, column=1, sticky=N+S+W)
self.liste.bind('', self.onSelect)

_The error is:_
Traceback (most recent call last):
  File "./observerAppliGraphique.py", line 118, in 
app=App()
  File "./observerAppliGraphique.py", line 37, in __init__
self.sujet.attach(self.nom)
  File "/home/karim/guiObserver/observable.py", line 11, in attach
self._observers.append(observer)
AttributeError: 'ListObservable' object has no attribute '_observers'

And the Observable class is:

class Observable(object):
"""Sujet a observer"""
def __init__(self):
self._observers = []
print('constructeur observable')

def attach(self, observer):
"""Attache un nouvel observateur"""
self._observers.append(observer)

def detach(self, observer):
"""Retire un nouvel observateur"""
self._observers.remove(observer)

def notify(self):
"""Avertit tous les observateurs que l'observable change d'etat"""
for observer in self._observers:
observer.update()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why super does not work !

2011-01-17 Thread Izz ad-Din Ruhulessin
It looks like because of something Observable doesn't have that attribute.
Could you post the ListBox class?

2011/1/17 Karim 

>
>
> Hello,
>
> I implemented Observer DP on a listbox (Tkinter) as follows and I don't
> understand why super() is not working and Observable.__init__(self) is
> working, cf below:
>
> class ListObservable(Listbox, Observable):
> """Creation de widget Listbox"""
> def __init__(self):
> super(ListObservable, self).__init__()
> #Observable.__init__(self)
> self._value = None
> self.listeContenu = StringVar()
> self.listeContenu.set(' '.join(sorted(data_base.keys(
> self.liste = Listbox(listvariable=self.listeContenu,
> selectmode='single')
> self.liste.grid(row=0, column=1, sticky=N+S+W)
> self.liste.bind('', self.onSelect)
>
> *The error is:*
> Traceback (most recent call last):
>   File "./observerAppliGraphique.py", line 118, in 
> app=App()
>   File "./observerAppliGraphique.py", line 37, in __init__
> self.sujet.attach(self.nom)
>   File "/home/karim/guiObserver/observable.py", line 11, in attach
> self._observers.append(observer)
> AttributeError: 'ListObservable' object has no attribute '_observers'
>
> And the Observable class is:
>
> class Observable(object):
> """Sujet a observer"""
> def __init__(self):
> self._observers = []
> print('constructeur observable')
>
> def attach(self, observer):
> """Attache un nouvel observateur"""
> self._observers.append(observer)
>
> def detach(self, observer):
> """Retire un nouvel observateur"""
> self._observers.remove(observer)
>
> def notify(self):
> """Avertit tous les observateurs que l'observable change d'etat"""
> for observer in self._observers:
> observer.update()
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is __weakref__ ?

2011-01-17 Thread Steven D'Aprano

Karim wrote:


Hello,

I am wondering what is this special class attribut. I know __dict__, 
slots. I use slots = [] when I want to use a read only class.


(1) slots = [] doesn't do anything special. You have misspelled __slots__.


(2) Classes don't become read only just because you add __slots__ to 
them. All you prevent is adding extra attributes, and why would you wish 
to do that? What harm does it do to you if the caller wants to add extra 
information to your class instances? All that does is make your class 
less useful. I have often wished I could add extra attributes to 
builtins like strings, ints, lists and so forth, but you can't:


>>> result = 42
>>> result.extra_info = 0.1
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'int' object has no attribute 'extra_info'

I understand why this is the case -- it's a memory optimization -- but 
it's a bloody nuisance. Don't repeat it if you don't have to.



(3) Even if it worked the way you think it works, it is an abuse of 
__slots__. __slots__ is not a mechanism for "read only classes", it is a 
memory optimization for when you need tens or hundreds of millions of 
instances.




But is anyone could explain with a little example the use of __weakref__?


Have you read the Fine Manual?

http://docs.python.org/reference/datamodel.html#slots


>>> class K1(object):
... __slots__ = []  # Don't support weak-refs.
...
>>> class K2(object):
...__slots__ = '__weakref__'  # Do support weak-refs.
...
>>> import weakref
>>> k1 = K1()
>>> k2 = K2()
>>> weakref.ref(k1)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: cannot create weak reference to 'K1' object
>>> weakref.ref(k2)




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why super does not work !

2011-01-17 Thread Dave Angel

On 01/-10/-28163 02:59 PM, Karim wrote:



Hello,

I implemented Observer DP on a listbox (Tkinter) as follows and I don't
understand why super() is not working and Observable.__init__(self) is
working, cf below:

class ListObservable(Listbox, Observable):
"""Creation de widget Listbox"""
def __init__(self):
super(ListObservable, self).__init__()
#Observable.__init__(self)
self._value = None
self.listeContenu = StringVar()
self.listeContenu.set(' '.join(sorted(data_base.keys(
self.liste = Listbox(listvariable=self.listeContenu, selectmode='single')
self.liste.grid(row=0, column=1, sticky=N+S+W)
self.liste.bind('', self.onSelect)

_The error is:_
Traceback (most recent call last):
File "./observerAppliGraphique.py", line 118, in 
app=App()
File "./observerAppliGraphique.py", line 37, in __init__
self.sujet.attach(self.nom)
File "/home/karim/guiObserver/observable.py", line 11, in attach
self._observers.append(observer)
AttributeError: 'ListObservable' object has no attribute '_observers'

And the Observable class is:

class Observable(object):
"""Sujet a observer"""
def __init__(self):
self._observers = []
print('constructeur observable')

def attach(self, observer):
"""Attache un nouvel observateur"""
self._observers.append(observer)

def detach(self, observer):
"""Retire un nouvel observateur"""
self._observers.remove(observer)

def notify(self):
"""Avertit tous les observateurs que l'observable change d'etat"""
for observer in self._observers:
observer.update()

Just looking at what you supply, I'd suppose that ListBox doesn't 
correctly call super() in its own __init__() method.


So I took a look at Tkinter.py, and sure enough, it just calls its own 
direct parent, Widget.l


super() only works if all the classes you use are done consistently.

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why super does not work !

2011-01-17 Thread Luke Paireepinart
I think it might be related to your multiple inheritance, maybe super is 
calling the init of observable on the listbox portion or something? I hardly 
ever do multiple inheritance so I'm not sure. What happens if you swap 
observable to be the first one?

-
Sent from a mobile device. Apologies for brevity and top-posting.
-

On Jan 17, 2011, at 3:47 PM, Karim  wrote:

> 
> 
> Hello,
> 
> I implemented Observer DP on a listbox (Tkinter) as follows and I don't 
> understand why super() is not working and Observable.__init__(self) is 
> working, cf below:
> 
> class ListObservable(Listbox, Observable):
> """Creation de widget Listbox"""
> def __init__(self):
> super(ListObservable, self).__init__()
> #Observable.__init__(self)
> self._value = None 
> self.listeContenu = StringVar()
> self.listeContenu.set(' '.join(sorted(data_base.keys(
> self.liste = Listbox(listvariable=self.listeContenu, 
> selectmode='single')
> self.liste.grid(row=0, column=1, sticky=N+S+W)
> self.liste.bind('', self.onSelect)
> 
> The error is:
> Traceback (most recent call last):
>   File "./observerAppliGraphique.py", line 118, in 
> app=App()
>   File "./observerAppliGraphique.py", line 37, in __init__
> self.sujet.attach(self.nom)
>   File "/home/karim/guiObserver/observable.py", line 11, in attach
> self._observers.append(observer)
> AttributeError: 'ListObservable' object has no attribute '_observers'
> 
> And the Observable class is:
> 
> class Observable(object):
> """Sujet a observer"""
> def __init__(self):
> self._observers = []
> print('constructeur observable')
> 
> def attach(self, observer):
> """Attache un nouvel observateur"""
> self._observers.append(observer)
> 
> def detach(self, observer):
> """Retire un nouvel observateur"""
> self._observers.remove(observer)
> 
> def notify(self):
> """Avertit tous les observateurs que l'observable change d'etat"""
> for observer in self._observers:
> observer.update()
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exactly duplicating strftime behavior?

2011-01-17 Thread Hugo Arts
On Mon, Jan 17, 2011 at 8:29 PM, Izz ad-Din Ruhulessin
 wrote:
> Hi all,
> I'm designing a module which aims to provide full compatibility with
> Pythons' datetime module.
> However, I can't find out how some operators in strftime function, namely:
> those who use the locale. (%a, %A, %b, etc.)
> How do I access this locale and it's values?
> Thanks in advance.
> Kind regards,
> Izz ad-Din

Check out the locale module:

http://docs.python.org/library/locale.html#locale.nl_langinfo

HTH,
Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why super does not work !

2011-01-17 Thread Steven D'Aprano

Karim wrote:



Hello,

I implemented Observer DP on a listbox (Tkinter) as follows and I don't 
understand why super() is not working and Observable.__init__(self) is 
working, cf below:


You seem to be confused about your class design. On the one hand, you 
inherit from Listbox, but then you *also* use composition and/or 
delegation on a Listbox instance:


class ListObservable(Listbox, Observable):
def __init__(self):
[...]
self.liste = Listbox(listvariable=self.listeContenu,
 selectmode='single')


That means that a ListObservable instance both *is* a Listbox and 
*contains* a Listbox at the same time. I'm not saying this is 
necessarily wrong, but it is unusual, and confuses the model. At the 
very least, you need to document why you have done this.




class ListObservable(Listbox, Observable):
"""Creation de widget Listbox"""
def __init__(self):
super(ListObservable, self).__init__()
#Observable.__init__(self)


Are both Listbox and Observable documented as suitable for multiple 
inheritance? My guess is that Listbox is not, and I can see from your 
source code that Observable is *not* suitable for multiple inheritance.


If Listbox is documented as suitable for multiple inheritance, then it 
is a bug in Listbox. If it is not, then it is a bug in your code, by 
using it for multiple inheritance.


Multiple inheritance in Python is cooperative, not enforced, and it is 
tricky to get right and is *very* sensitive to any class which fails to 
cooperate. Thousands and thousands of words have been written on the 
perils and difficulties of multiple inheritance, particularly by Michele 
Simionato who I consider to be THE authority on MI in Python.


Some of the most important articles are:

Michele Simionato:
Things to Know About Python Super
http://www.artima.com/weblogs/viewpost.jsp?thread=236275
http://www.artima.com/weblogs/viewpost.jsp?thread=236278
http://www.artima.com/weblogs/viewpost.jsp?thread=237121
Mixins considered harmful:
http://www.artima.com/weblogs/viewpost.jsp?thread=246341
http://www.artima.com/weblogs/viewpost.jsp?thread=246483
http://www.artima.com/weblogs/viewpost.jsp?thread=254367
http://www.artima.com/weblogs/viewpost.jsp?thread=254507
Generic functions vs mixins:
http://www.artima.com/weblogs/viewpost.jsp?thread=237764
Straits:
http://www.artima.com/weblogs/viewpost.jsp?thread=246488

James Knight:
Python's Super Considered Harmful
http://fuhm.net/super-harmful/


Summary: this is *not* a bug in super. It's really a side-effect of the 
fact that multiple inheritance itself is often the wrong thing to use, 
and even when it is right, it is often tricky to get it right. To put it 
another way: don't use multiple inheritance unless you have to, there 
are better ways, such as by composition.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why super does not work !

2011-01-17 Thread Alan G
Steven D'Aprano  pearwood.info> writes:

> fact that multiple inheritance itself is often the wrong thing to use, 
> and even when it is right, it is often tricky to get it right. To put it 
> another way: don't use multiple inheritance unless you have to, there 
> are better ways, such as by composition.

Or use a language where MI is the normal and idiomatic way 
to do things because the language assumes it and so it just 
works. There are very few such languages but Lisp is one :-)

Sadly Python isn't, and when using MI I always avoid super()
Which is a huge shame since MI is where super() should 
be most useful... But in my experience MI in Python is 
definitely a place where explicit is better than implicit.

Alan G.



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why super does not work !

2011-01-17 Thread Karim


Thanks Izz, Luke, Steven and Alan!
That's I figured out with MI and super.
Steven I understand the point to have Listbox contains a Listbox.
Before the code was in App class and I extracted it to do an outside 
class making the mistake.

But magic of Python it's working (but I know it's awful).
The code is working but I am not totally happy because of many 
EntryObserver almost identical objects (except from update and grid() 
options)

Is it possible to simplify this structure?

Regards
Karim

The rest of the code is below:

#!/usr/bin/env python2.7
"""Module ObserverGraphique.py

Une implementation du design pattern Observer.
"""


from Tkinter import *
from observable import Observable
from observer import AbstractObserver


data_base = {
'Employe1': ['Joel',   'Durant',  '0623'],
'Employe2': ['Marc',   'Donce',   '0624'],
'Employe3': ['George', 'Roux','0625'],
'Employe4': ['Alain',  'Richard', '0626']
}


__all__ = ['App', 'ListObservable', 'Entry1Observer', 'Entry2Observer', 
'Entry3Observer']



class App(Frame):
"""Application graphique avec Tkinter implementant un Observer 
Design Pattern."""

def __init__(self, master=None):
Frame.__init__(self, master)
self.master.title("Exemple : Observer Design Pattern")
self.grid()
self.createLabels()
self.createObservable()
self.createObservers()
self.registerObservers()

   def createLabels(self):
"""Creation de widgets Label"""
self.label1 = Label(text="Nom :")
self.label2 = Label(text="Prenom :")
self.label3 = Label(text="Poste :")
self.label1.grid(row=1, column=1, sticky=W)
self.label2.grid(row=2, column=1, sticky=W)
self.label3.grid(row=3, column=1, sticky=W)

def createObservable(self):
"""Creation de la listBox observable."""
self.sujet  = ListObservable()

def createObservers(self):
"""Creation des champs d'entre texte observateurs de la liste."""
self.nom= Entry1Observer(self.sujet)
self.prenom = Entry2Observer(self.sujet)
self.poste  = Entry3Observer(self.sujet)

def registerObservers(self):
"""Enregistrement des observateurs."""
self.sujet.attach(self.nom)
self.sujet.attach(self.prenom)
self.sujet.attach(self.poste)

class ListObservable(Listbox, Observable):
"""Creation de widget Listbox"""
def __init__(self):
#super(ListObservable, self).__init__()
Observable.__init__(self)
self._value = None
self.listeContenu = StringVar()
self.listeContenu.set(' '.join(sorted(data_base.keys(
self.liste = Listbox(listvariable=self.listeContenu, 
selectmode='single')

self.liste.grid(row=0, column=1, sticky=N+S+W)
self.liste.bind('', self.onSelect)
self.liste.selection_set(0)

def onSelect(self, e):
if not self.liste.curselection():
self.setValue(0)
else:
self.setValue(self.liste.get(self.liste.curselection()))
self.notify()

def setValue(self, select):
self._value = select

def getValue(self):
return self._value

class Entry1Observer(Entry, AbstractObserver):
"""Creation de widget Entry 1"""
def __init__(self, sujet=None):
#super(Entry1Observer, self).__init__(sujet)
AbstractObserver.__init__(self, sujet)
self.text = StringVar()
self.entry = Entry(textvariable=self.text)
self.entry.grid(row=1, column=2)

def update(self):
a = self.sujet.getValue()
self.text.set(data_base[a][1])
print a

class Entry2Observer(Entry, AbstractObserver):
"""Creation de widget Entry 2"""
def __init__(self, sujet=None):
AbstractObserver.__init__(self, sujet)
self.text  = StringVar()
self.entry = Entry(textvariable=self.text)
self.entry.grid(row=2, column=2)

def update(self):
a = self.sujet.getValue()
self.text.set(data_base[a][0])

class Entry3Observer(Entry, AbstractObserver):
"""Creation de widget Entry"""
def __init__(self, sujet=None):
AbstractObserver.__init__(self, sujet)
self.text  = StringVar()
self.entry = Entry(textvariable=self.text)
self.entry.grid(row=3, column=2)

def update(self):
a = self.sujet.getValue()
self.text.set(data_base[a][2])


if __name__ == '__main__':
app=App()
app.mainloop()

# - end of file - #

class AbstractObserver(object):
"""Interface general des observateurs"""
def __init__(self, sujet):
"""Constructeur"""
self.sujet = sujet

def update(self):
"""Methode a implementer par les observateurs"""
pass


On 01/18/2011 02:32 AM, Alan G wrote:

Steven D'Aprano  pearwood.info>  writes:


fact that multiple inheritance itself is often the wrong thing to use,
and even when i

Re: [Tutor] Exactly duplicating strftime behavior?

2011-01-17 Thread Izz ad-Din Ruhulessin
Hi Hugo,

Problem solved, thanks!

Kind regards,

Izz ad-Din

2011/1/17 Hugo Arts 

> On Mon, Jan 17, 2011 at 8:29 PM, Izz ad-Din Ruhulessin
>  wrote:
> > Hi all,
> > I'm designing a module which aims to provide full compatibility with
> > Pythons' datetime module.
> > However, I can't find out how some operators in strftime function,
> namely:
> > those who use the locale. (%a, %A, %b, etc.)
> > How do I access this locale and it's values?
> > Thanks in advance.
> > Kind regards,
> > Izz ad-Din
>
> Check out the locale module:
>
> http://docs.python.org/library/locale.html#locale.nl_langinfo
>
> HTH,
> Hugo
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor