Saturday, January 18, 2014

comp.lang.python - 26 new messages in 9 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* Guessing the encoding from a BOM - 5 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/1b4501ed3e9e2af1?hl=en
* doctests compatibility for python 2 & python 3 - 8 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/e83b94c8f7e04717?hl=en
* interactive help on the base object - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/43d86819eed5d4f5?hl=en
* EuroPython has a new blog - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/a14ac76a057e422a?hl=en
* EuroPython Society website now live - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/8d93cc0709a66398?hl=en
* advice and comment wanted on first tkinter program - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/f800a6855b860c2f?hl=en
* Python declarative - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/d3cb0aca7152f06f?hl=en
* python2.6 needed as an aptitude package as dependency - 2 messages, 2
authors
http://groups.google.com/group/comp.lang.python/t/785d1b0f7843ab4c?hl=en
* Python 3.x adoption - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/3d5defc6634ef3b4?hl=en

==============================================================================
TOPIC: Guessing the encoding from a BOM
http://groups.google.com/group/comp.lang.python/t/1b4501ed3e9e2af1?hl=en
==============================================================================

== 1 of 5 ==
Date: Fri, Jan 17 2014 1:47 am
From: Mark Lawrence



On 17/01/2014 09:43, Chris Angelico wrote:
> On Fri, Jan 17, 2014 at 8:10 PM, Mark Lawrence <breamoreboy@yahoo.co.uk> wrote:
>> Slight aside, any chance of changing the subject of this thread, or even
>> ending the thread completely? Why? Every time I see it I picture Inspector
>> Clouseau, "A BOM!!!" :)
>
> Special delivery, a berm! Were you expecting one?
>
> ChrisA
>

By coincidence I'm just off to collect a special delievry, of what I
don't yet know.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence





== 2 of 5 ==
Date: Fri, Jan 17 2014 1:58 am
From: Chris Angelico


On Fri, Jan 17, 2014 at 8:47 PM, Mark Lawrence <breamoreboy@yahoo.co.uk> wrote:
> On 17/01/2014 09:43, Chris Angelico wrote:
>>
>> On Fri, Jan 17, 2014 at 8:10 PM, Mark Lawrence <breamoreboy@yahoo.co.uk>
>> wrote:
>>>
>>> Slight aside, any chance of changing the subject of this thread, or even
>>> ending the thread completely? Why? Every time I see it I picture
>>> Inspector
>>> Clouseau, "A BOM!!!" :)
>>
>>
>> Special delivery, a berm! Were you expecting one?
>>
>> ChrisA
>>
>
> By coincidence I'm just off to collect a special delievry, of what I don't
> yet know.

Did you write a script to buy you something for a dollar off eBay
every day? Day six gets interesting, as I understand it.

ChrisA




== 3 of 5 ==
Date: Fri, Jan 17 2014 8:26 am
From: Pete Forman


Rustom Mody <rustompmody@gmail.com> writes:

> On Friday, January 17, 2014 7:10:05 AM UTC+5:30, Tim Chase wrote:
>> On 2014-01-17 11:14, Chris Angelico wrote:
>> > UTF-8 specifies the byte order
>> > as part of the protocol, so you don't need to mark it.
>
>> You don't need to mark it when writing, but some idiots use it
>> anyway. If you're sniffing a file for purposes of reading, you need
>> to look for it and remove it from the actual data that gets returned
>> from the file--otherwise, your data can see it as corruption. I end
>> up with lots of CSV files from customers who have polluted it with
>> Notepad or had Excel insert some UTF-8 BOM when exporting. This
>> means my first column-name gets the BOM prefixed onto it when the
>> file is passed to csv.DictReader, grr.
>
> And its part of the standard:
> Table 2.4 here
> http://www.unicode.org/versions/Unicode5.0.0/ch02.pdf

It would have been nice if there was an eighth encoding scheme defined
there UTF-8NB which would be UTF-8 with BOM not allowed.
--
Pete Forman




== 4 of 5 ==
Date: Fri, Jan 17 2014 8:30 am
From: Rustom Mody


On Friday, January 17, 2014 9:56:28 PM UTC+5:30, Pete Forman wrote:
> Rustom Mody writes:

> > On Friday, January 17, 2014 7:10:05 AM UTC+5:30, Tim Chase wrote:
> >> On 2014-01-17 11:14, Chris Angelico wrote:
> >> > UTF-8 specifies the byte order
> >> > as part of the protocol, so you don't need to mark it.
> >> You don't need to mark it when writing, but some idiots use it
> >> anyway. If you're sniffing a file for purposes of reading, you need
> >> to look for it and remove it from the actual data that gets returned
> >> from the file--otherwise, your data can see it as corruption. I end
> >> up with lots of CSV files from customers who have polluted it with
> >> Notepad or had Excel insert some UTF-8 BOM when exporting. This
> >> means my first column-name gets the BOM prefixed onto it when the
> >> file is passed to csv.DictReader, grr.
> > And its part of the standard:
> > Table 2.4 here
> > http://www.unicode.org/versions/Unicode5.0.0/ch02.pdf

> It would have been nice if there was an eighth encoding scheme defined
> there UTF-8NB which would be UTF-8 with BOM not allowed.

If you or I break a standard then, well, we broke a standard.
If Microsoft breaks a standard the standard is obliged to change.

Or as the saying goes, everyone is equal though some are more equal.




== 5 of 5 ==
Date: Fri, Jan 17 2014 8:33 am
From: Chris Angelico


On Sat, Jan 18, 2014 at 3:26 AM, Pete Forman <petef4+usenet@gmail.com> wrote:
> It would have been nice if there was an eighth encoding scheme defined
> there UTF-8NB which would be UTF-8 with BOM not allowed.

Or call that one UTF-8, and the one with the marker can be UTF-8-MS-NOTEPAD.

ChrisA





==============================================================================
TOPIC: doctests compatibility for python 2 & python 3
http://groups.google.com/group/comp.lang.python/t/e83b94c8f7e04717?hl=en
==============================================================================

== 1 of 8 ==
Date: Fri, Jan 17 2014 3:16 am
From: Robin Becker


I have some problems making some doctests for python2 code compatible with
python3. The problem is that as part of our approach we are converting the code
to use unicode internally. So we allow eihter byte strings or unicode in inputs,
but we are trying to convert to unicode outputs.

That makes doctests quite hard as

def func(a):
"""
>>> func(u'aaa')
'aaa'
"""
return a

fails in python2 whilst

def func(a):
"""
>>> func(u'aaa')
u'aaa'
"""
return a

fails in python3. Aside from changing the tests so they look like
"""
>>> func(u'aaa')==u'aaa'
True
"""
which make the test utility harder. If the test fails I don't see the actual
outcome and expected I see expected True got False.

Is there an easy way to make these kinds of tests work in python 2 & 3?
--
Robin Becker





== 2 of 8 ==
Date: Fri, Jan 17 2014 3:24 am
From: Chris Angelico


On Fri, Jan 17, 2014 at 10:16 PM, Robin Becker <robin@reportlab.com> wrote:
> Aside from changing the tests so they look like
> """
> >>> func(u'aaa')==u'aaa'
> True
> """

Do your test strings contain any non-ASCII characters? If not, you
might be able to do this:

def func(a):
"""
>>> str(func(u'aaa'))
'aaa'
"""
return a

which should work in both. In Py3, the str() call will do nothing, and
it'll compare correctly; in Py2, it'll convert it into a byte string,
which will repr() without the 'u'.

I don't think it's possible to monkey-patch unicode.__repr__ to not
put the u'' prefix on, but if there is a way, that'd possibly be more
convenient.

ChrisA




== 3 of 8 ==
Date: Fri, Jan 17 2014 3:30 am
From: Chris Angelico


On Fri, Jan 17, 2014 at 10:24 PM, Chris Angelico <rosuav@gmail.com> wrote:
> Do your test strings contain any non-ASCII characters? If not, you
> might be able to do this:
>
> def func(a):
> """
> >>> str(func(u'aaa'))
> 'aaa'
> """
> return a

Actually, probably better than that:

def func(a):
"""
>>> text(func(u'aaa'))
'aaa'
"""
return a

try:
class text(unicode): # Will throw NameError in Py3
def __repr__(self):
return unicode.__repr__(self)[1:]
except NameError:
# Python 3 doesn't need this wrapper.
text = str

Little helper class that does what I don't think monkey-patching will
do. I've tested this and it appears to work in both 2.7.4 and 3.4.0b2,
but that doesn't necessarily mean that the repr of any given Unicode
string will be exactly the same on both versions. It's likely to be
better than depending on the strings being ASCII, though.

ChrisA




== 4 of 8 ==
Date: Fri, Jan 17 2014 3:41 am
From: Steven D'Aprano


On Fri, 17 Jan 2014 11:16:17 +0000, Robin Becker wrote:

> I have some problems making some doctests for python2 code compatible
> with python3. The problem is that as part of our approach we are
> converting the code to use unicode internally. So we allow eihter byte
> strings or unicode in inputs, but we are trying to convert to unicode
> outputs.

Alas, I think you've run into one of the weaknesses of doctest. Don't get
me wrong, I am a huge fan of doctest, but it is hard to write polyglot
string tests with it, as you have discovered.

However, you may be able to get 95% of the way by using print.

def func(a):
"""
>>> print(func(u'aaa'))
aaa
"""
return a

ought to behave identically in both Python 2 and Python 3.3, provided you
only print one object at a time. This ought to work with both ASCII and
non-ASCII (at least in the BMP).



--
Steven




== 5 of 8 ==
Date: Fri, Jan 17 2014 4:12 am
From: Robin Becker


On 17/01/2014 11:41, Steven D'Aprano wrote:
> def func(a):
> """
> >>> print(func(u'aaa'))
> aaa
> """
> return a
I think this approach seems to work if I turn the docstring into unicode

def func(a):
u"""
>>> print(func(u'aaa\u020b'))
aaa\u020b
"""
return a
def _doctest():
import doctest
doctest.testmod()

if __name__ == "__main__":
_doctest()

If I leave the u off the docstring it goes wrong in python 2.7. I also tried to
put an encoding onto the file and use the actual utf8 characters ie

# -*- coding: utf-8 -*-
def func(a):
"""
>>> print(func(u'aaa\u020b'))
aaaȋ
"""
return a
def _doctest():
import doctest
doctest.testmod()

and that works in python3, but fails in python 2 with this
> (py27) C:\code\hg-repos>python tdt1.py
> C:\python\Lib\doctest.py:1531: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - in
> terpreting them as being unequal
> if got == want:
> C:\python\Lib\doctest.py:1551: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - in
> terpreting them as being unequal
> if got == want:
> **********************************************************************
> File "tdt1.py", line 4, in __main__.func
> Failed example:
> print(func(u'aaa\u020b'))
> Expected:
> aaaȋ
> Got:
> aaaȋ
> **********************************************************************
> 1 items had failures:
> 1 of 1 in __main__.func
> ***Test Failed*** 1 failures.


--
Robin Becker





== 6 of 8 ==
Date: Fri, Jan 17 2014 4:14 am
From: Robin Becker


On 17/01/2014 11:30, Chris Angelico wrote:
> On Fri, Jan 17, 2014 at 10:24 PM, Chris Angelico <rosuav@gmail.com> wrote:
>> Do your test strings contain any non-ASCII characters? If not, you
>> might be able to do this:
>>
>> def func(a):
>> """
>> >>> str(func(u'aaa'))
>> 'aaa'
>> """
>> return a
>
> Actually, probably better than that:
>
> def func(a):
> """
> >>> text(func(u'aaa'))
> 'aaa'
> """
> return a
>
> try:
> class text(unicode): # Will throw NameError in Py3
> def __repr__(self):
> return unicode.__repr__(self)[1:]
> except NameError:
> # Python 3 doesn't need this wrapper.
> text = str
>
> Little helper class that does what I don't think monkey-patching will
> do. I've tested this and it appears to work in both 2.7.4 and 3.4.0b2,
> but that doesn't necessarily mean that the repr of any given Unicode
> string will be exactly the same on both versions. It's likely to be
> better than depending on the strings being ASCII, though.
>
> ChrisA
>

I tried this approach with a few more complicated outcomes and they fail in
python2 or 3 depending on how I try to render the result in the doctest.
--
Robin Becker





== 7 of 8 ==
Date: Fri, Jan 17 2014 7:27 am
From: Steven D'Aprano


On Fri, 17 Jan 2014 12:12:35 +0000, Robin Becker wrote:

> On 17/01/2014 11:41, Steven D'Aprano wrote:
>> def func(a):
>> """
>> >>> print(func(u'aaa'))
>> aaa
>> """
>> return a
>
> I think this approach seems to work if I turn the docstring into unicode
>
> def func(a):
> u"""
> >>> print(func(u'aaa\u020b'))
> aaa\u020b
> """
> return a

Good catch! Without the u-prefix, the \u... is not interpreted as an
escape sequence, but as a literal backslash-u.


> If I leave the u off the docstring it goes wrong in python 2.7. I also
> tried to put an encoding onto the file and use the actual utf8
> characters ie
>
> # -*- coding: utf-8 -*-
> def func(a):
> """
> >>> print(func(u'aaa\u020b'))
> aaaȋ
> """
> return a

There seems to be some mojibake in your post, which confuses issues.

You refer to \u020b, which is LATIN SMALL LETTER I WITH INVERTED BREVE.
At least, that's what it ought to be. But in your post, it shows up as
the two character mojibake, ╚ followed by ï (BOX DRAWINGS DOUBLE UP AND
RIGHT followed by LATIN SMALL LETTER I WITH DIAERESIS). It appears that
your posting software somehow got confused and inserted the two
characters which you would have got using cp-437 while claiming that they
are UTF-8. (Your post is correctly labelled as UTF-8.)

I'm confident that the problem isn't with my newsreader, Pan, because it
is pretty damn good at getting encodings right, but also because your
post shows the same mojibake in the email archive:

https://mail.python.org/pipermail/python-list/2014-January/664771.html

To clarify: you tried to show \u020B as a literal. As a literal, it ought
to be the single character ȋ which is a lower case I with curved accent on
top. The UTF-8 of that character is b'\xc8\x8b', which in the cp-437 code
page is two characters ╚ ï.

py> '\u020b'.encode('utf8').decode('cp437')
'ȋ'

Hence, mojibake.


> def _doctest():
> import doctest
> doctest.testmod()
>
> and that works in python3, but fails in python 2 with this
>> (py27) C:\code\hg-repos>python tdt1.py C:\python\Lib\doctest.py:1531:
>> UnicodeWarning: Unicode equal comparison failed to convert both
>> arguments to Unicode - in terpreting them as being unequal
>> if got == want:
>> C:\python\Lib\doctest.py:1551: UnicodeWarning: Unicode equal comparison
>> failed to convert both arguments to Unicode - in terpreting them as
>> being unequal

I cannot replicate this specific exception. I think it may be a side-
effect of you being on Windows. (I'm on Linux, and everything is UTF-8.)

>> if got == want:
>> **********************************************************************
>> File "tdt1.py", line 4, in __main__.func Failed example:
>> print(func(u'aaa\u020b'))
>> Expected:
>> aaaȋ
>> Got:
>> aaaȋ

The difficulty here is that it is damn near impossible to sort out which,
if any, bits are mojibake inserted by your posting software, which by
your editor, your terminal, which by Python, and which are artifacts of
the doctest system.

The usual way to debug these sorts of errors is to stick a call to repr()
just before the print.

print(repr(func(u'aaa\u020b')))



--
Steven




== 8 of 8 ==
Date: Fri, Jan 17 2014 8:17 am
From: Robin Becker


On 17/01/2014 15:27, Steven D'Aprano wrote:
..........
>>
>> # -*- coding: utf-8 -*-
>> def func(a):
>> """
>> >>> print(func(u'aaa\u020b'))
>> aaaȋ
>> """
>> return a
>
> There seems to be some mojibake in your post, which confuses issues.
>
> You refer to \u020b, which is LATIN SMALL LETTER I WITH INVERTED BREVE.
> At least, that's what it ought to be. But in your post, it shows up as
> the two character mojibake, ╚ followed by ï (BOX DRAWINGS DOUBLE UP AND
> RIGHT followed by LATIN SMALL LETTER I WITH DIAERESIS). It appears that
> your posting software somehow got confused and inserted the two
> characters which you would have got using cp-437 while claiming that they
> are UTF-8. (Your post is correctly labelled as UTF-8.)
>
> I'm confident that the problem isn't with my newsreader, Pan, because it
> is pretty damn good at getting encodings right, but also because your
> post shows the same mojibake in the email archive:
>
> https://mail.python.org/pipermail/python-list/2014-January/664771.html
>
> To clarify: you tried to show \u020B as a literal. As a literal, it ought
> to be the single character ȋ which is a lower case I with curved accent on
> top. The UTF-8 of that character is b'\xc8\x8b', which in the cp-437 code
> page is two characters ╚ ï.

when I edit the file in vim with ut88 encoding I do see your ȋ as the literal.
However, as you note I'm on windows and no amount of cajoling will get it to
work reasonably so my printouts are broken. So on windows

(py27) C:\code\hg-repos>python -c"print(u'aaa\u020b')"
aaaȋ

on my linux

$ python2 -c"print(u'aaa\u020b')"
aaaȋ

$ python2 tdt1.py
/usr/lib/python2.7/doctest.py:1531: UnicodeWarning: Unicode equal comparison
failed to convert both arguments to Unicode - interpreting them as being unequal
if got == want:
/usr/lib/python2.7/doctest.py:1551: UnicodeWarning: Unicode equal comparison
failed to convert both arguments to Unicode - interpreting them as being unequal
if got == want:
**********************************************************************
File "tdt1.py", line 4, in __main__.func
Failed example:
print(func(u'aaa\u020b'))
Expected:
aaaȋ
Got:
aaaȋ
**********************************************************************
1 items had failures:
1 of 1 in __main__.func
***Test Failed*** 1 failures.
robin@everest ~/tmp:
$ cat tdt1.py
# -*- coding: utf-8 -*-
def func(a):
"""
>>> print(func(u'aaa\u020b'))
aaaȋ
"""
return a
def _doctest():
import doctest
doctest.testmod()

if __name__ == "__main__":
_doctest()
robin@everest ~/tmp:

so the error persists with our without copying errors.

Note that on my putty terminal I don't see the character properly (I see unknown
glyph square box), but it copies OK.
--
Robin Becker






==============================================================================
TOPIC: interactive help on the base object
http://groups.google.com/group/comp.lang.python/t/43d86819eed5d4f5?hl=en
==============================================================================

== 1 of 1 ==
Date: Fri, Jan 17 2014 4:25 am
From: Jean-Michel Pichavant


----- Original Message -----
> On 17/01/2014 01:00, Terry Reedy wrote:
> > On 12/6/2013 8:35 PM, Terry Reedy wrote:
> >> On 12/6/2013 12:03 PM, Mark Lawrence wrote:
> >>> Is it just me, or is this basically useless?
> >>>
> >>> >>> help(object)
> >>> Help on class object in module builtins:
> >>>
> >>> class object
> >>> | The most base type
> >>
> >> Given that this can be interpreted as 'least desirable', it could
> >> definitely be improved.
> >>
> >>> Surely a few more words,
> >>
> >> How about something like.
> >>
> >> '''The default top superclass for all Python classes.
> >>
> >> Its methods are inherited by all classes unless overriden.
> >> '''
> >>
> >> When you have 1 or more concrete suggestions for the docstring,
> >> open a
> >> tracker issue.
> >
> > At Mark's invitation, I have done so.
> > http://bugs.python.org/issue20285
> >
>
> Thanks, I've altered my will accordingly :)
>
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence

The issue is tagged 2.7. Is object the superclass of all classes in 2.7 ?
I'm asking because in 2.5, it is not (old/new style).

JM


-- IMPORTANT NOTICE:

The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.





==============================================================================
TOPIC: EuroPython has a new blog
http://groups.google.com/group/comp.lang.python/t/a14ac76a057e422a?hl=en
==============================================================================

== 1 of 2 ==
Date: Fri, Jan 17 2014 4:37 am
From: "M.-A. Lemburg"


The EuroPython Society has setup a new blog for EuroPython in its
efforts to provide more conference facilities for the EuroPython
organization and to enhance the EuroPython attendee experience.

http://blog.europython.eu/

There�s an RSS feed in case you want to subscribe to it:

http://blog.europython.eu/rss

The blog itself is hosted on Tumblr, so you can also follow the blog
using your Tumblr account: log in, visit the blog and click �Follow" in
the upper right corner:

http://www.tumblr.com/follow/europython

If you�re looking for older blog entries, please check the
EuroPython 2013 blog, which lists the entries for 2011-2013:

https://ep2013.europython.eu/blog/

Enjoy,
--
Marc-Andre Lemburg
Director
EuroPython Society
http://www.europython-society.org/




== 2 of 2 ==
Date: Fri, Jan 17 2014 4:41 am
From: "Stéphane Wirtel"


Hi Marc-André,

Cool for EuroPython,

Good idea, I think we will use tumblr for a small blog for Python-FOSDEM.

Stef



On 17 Jan 2014, at 13:37, M.-A. Lemburg wrote:

> The EuroPython Society has setup a new blog for EuroPython in its
> efforts to provide more conference facilities for the EuroPython
> organization and to enhance the EuroPython attendee experience.
>
> http://blog.europython.eu/
>
> There's an RSS feed in case you want to subscribe to it:
>
> http://blog.europython.eu/rss
>
> The blog itself is hosted on Tumblr, so you can also follow the blog
> using your Tumblr account: log in, visit the blog and click "Follow" in
> the upper right corner:
>
> http://www.tumblr.com/follow/europython
>
> If you're looking for older blog entries, please check the
> EuroPython 2013 blog, which lists the entries for 2011-2013:
>
> https://ep2013.europython.eu/blog/
>
> Enjoy,
> --
> Marc-Andre Lemburg
> Director
> EuroPython Society
> http://www.europython-society.org/
> --
> https://mail.python.org/mailman/listinfo/python-list





==============================================================================
TOPIC: EuroPython Society website now live
http://groups.google.com/group/comp.lang.python/t/8d93cc0709a66398?hl=en
==============================================================================

== 1 of 1 ==
Date: Fri, Jan 17 2014 4:38 am
From: "M.-A. Lemburg"


The EuroPython Society has created a new website to collect
information on EuroPython, the society and its workings:

http://www.europython-society.org/

For those who don�t know: the society is a Swedish non-profit
organization which was formed in 2004 by the EuroPython organizers
to put on EuroPython conferences.

A new board was voted in at the EuroPython 2012 conference:

https://ep2013.europython.eu/blog/2012/07/08/change-board-europython-society

Given the size of EuroPython conferences, we�re working on formalizing
the EuroPython selection process, providing resources and arranging
with local teams to run EuroPython conferences:

http://www.europython-society.org/cfp

We consider the EuroPython Society the representation of the EuroPython
attendees, so if you have questions, requests for improvements or other
ideas on how to improve the series, please feel free to contact us:

http://www.europython-society.org/contact

You can also become members of the EuroPython Society at no charge and
then vote at the general assembly of the society. Please visit our
members page for more information:

http://www.europython-society.org/members

Enjoy,
--
Marc-Andre Lemburg
Director
EuroPython Society
http://www.europython-society.org/





==============================================================================
TOPIC: advice and comment wanted on first tkinter program
http://groups.google.com/group/comp.lang.python/t/f800a6855b860c2f?hl=en
==============================================================================

== 1 of 2 ==
Date: Fri, Jan 17 2014 5:20 am
From: Jean Dupont


Dear all,
I made a simple gui with tkinter. I can imagine there are things which I
did which are "not optimal". So what I ask is to comment on my code
preferable with snippets of code which show how to do improve my code.
#!/usr/bin/env python
import Tkinter
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(26,GPIO.OUT)
GPIO.setup(24,GPIO.OUT)
#hardware : connect 2 leds:
#board-pin 26 on/off led; control with buttons
#board-pin 24 led with pwm dimming and frequency; control via sliders
top = Tkinter.Tk()
top.geometry("600x400+310+290")
var1 = DoubleVar()
var2 = DoubleVar()
i=0
p=GPIO.PWM(24,1)
p.start(50)
def btn_on_cmd():
text3.configure(bg = "#00FF00")
text3.delete(0.1,END)
text3.insert("0.1","ON ")
GPIO.output(26,True)
def btn_off_cmd():
text3.configure(bg = "#FF4000")
text3.delete(0.1,END)
text3.insert("0.1","OFF")
GPIO.output(26, False)
def timer0():
global i
i=i+1
text1.delete(0.1,END)
text1.insert(4.2,"Timer: " + str(i))
label1.configure(text=time.strftime("%H:%M:%S"))
top.after(1000, timer0)
def Set_PWM(var1):
DC = float(var1)
p.ChangeDutyCycle(DC)
def Set_FREQ(var2):
FR = float(var2)
p.ChangeFrequency(FR)
btn_on = Button(top, text ="On", command = btn_on_cmd)
btn_on.place(x=10,y=100)
btn_off = Button(top, text ="Off", command = btn_off_cmd)
btn_off.place(x=100,y=100)
text1 =Text(top, bg = "#009BFF", font=("Helvetica",14), height = 1, width
= 15)
text1.place(x=5,y=5)
text3=Text(top, bg = "red", font=("Helvetica",12),height = 1, width = 4)
text3.place(x=60,y=60)
label1 = Label(top,relief=RAISED,bg =
"#EFF980",font=("Helvetica",14),height = 1, width = 15)
label1.place(x=5,y=350)
label2= Label(top,relief=RAISED,bg =
"#BFBFBF",font=("Helvetica",10),height = 1, text= "Freq (Hz)")
label2.place(x=420,y=320)
label3= Label(top,relief=RAISED,bg =
"#BFBFBF",font=("Helvetica",10),height = 1, text= "DC %")
label3.place(x=520,y=320)
slider1 = Scale(top,variable = var1,length = 300,resolution = 1,command =
Set_PWM)
slider1 = Scale(top,variable = var1,length = 300,resolution = 1,command = Set_PWM)
slider1.place(x=500,y=5)
slider1.set(50)
slider2 = Scale(top,variable = var2,length = 300,from_= 0.1, to = 50,resolution = 0.1,command = Set_FREQ)
slider2.place(x=400,y=5)
slider2.set(2)
timer0()
top.mainloop()
GPIO.cleanup()


thanks in advance
jean





== 2 of 2 ==
Date: Fri, Jan 17 2014 7:17 am
From: Peter Otten <__peter__@web.de>


Jean Dupont wrote:

> Dear all,
> I made a simple gui with tkinter. I can imagine there are things which I
> did which are "not optimal". So what I ask is to comment on my code
> preferable with snippets of code which show how to do improve my code.
> #!/usr/bin/env python
> import Tkinter
> import time
> import RPi.GPIO as GPIO
> GPIO.setmode(GPIO.BOARD)
> GPIO.setup(26,GPIO.OUT)
> GPIO.setup(24,GPIO.OUT)
> #hardware : connect 2 leds:
> #board-pin 26 on/off led; control with buttons
> #board-pin 24 led with pwm dimming and frequency; control via sliders
> top = Tkinter.Tk()
> top.geometry("600x400+310+290")
> var1 = DoubleVar()
> var2 = DoubleVar()
> i=0
> p=GPIO.PWM(24,1)
> p.start(50)
> def btn_on_cmd():
> text3.configure(bg = "#00FF00")
> text3.delete(0.1,END)
> text3.insert("0.1","ON ")
> GPIO.output(26,True)
> def btn_off_cmd():
> text3.configure(bg = "#FF4000")
> text3.delete(0.1,END)
> text3.insert("0.1","OFF")
> GPIO.output(26, False)
> def timer0():
> global i
> i=i+1
> text1.delete(0.1,END)
> text1.insert(4.2,"Timer: " + str(i))
> label1.configure(text=time.strftime("%H:%M:%S"))
> top.after(1000, timer0)
> def Set_PWM(var1):
> DC = float(var1)
> p.ChangeDutyCycle(DC)
> def Set_FREQ(var2):
> FR = float(var2)
> p.ChangeFrequency(FR)
> btn_on = Button(top, text ="On", command = btn_on_cmd)
> btn_on.place(x=10,y=100)
> btn_off = Button(top, text ="Off", command = btn_off_cmd)
> btn_off.place(x=100,y=100)
> text1 =Text(top, bg = "#009BFF", font=("Helvetica",14), height = 1, width
> = 15)
> text1.place(x=5,y=5)
> text3=Text(top, bg = "red", font=("Helvetica",12),height = 1, width = 4)
> text3.place(x=60,y=60)
> label1 = Label(top,relief=RAISED,bg =
> "#EFF980",font=("Helvetica",14),height = 1, width = 15)
> label1.place(x=5,y=350)
> label2= Label(top,relief=RAISED,bg =
> "#BFBFBF",font=("Helvetica",10),height = 1, text= "Freq (Hz)")
> label2.place(x=420,y=320)
> label3= Label(top,relief=RAISED,bg =
> "#BFBFBF",font=("Helvetica",10),height = 1, text= "DC %")
> label3.place(x=520,y=320)
> slider1 = Scale(top,variable = var1,length = 300,resolution = 1,command =
> Set_PWM)
> slider1 = Scale(top,variable = var1,length = 300,resolution = 1,command =
> Set_PWM) slider1.place(x=500,y=5)
> slider1.set(50)
> slider2 = Scale(top,variable = var2,length = 300,from_= 0.1, to =
> 50,resolution = 0.1,command = Set_FREQ) slider2.place(x=400,y=5)
> slider2.set(2)
> timer0()
> top.mainloop()
> GPIO.cleanup()
>
>
> thanks in advance
> jean

First and foremost a program has to do what the author wants it to do.
Everything else is secondary. You are likely to have such a program on your
machine, so congrats :)

However, the version you posted does not run, probably because you started
to replace

from Tkinter import *
top = Tk()
...
var1 = DoubleVar()

with the -- better --

import Tkinter
top = Tkinter.Tk()
...

but stopped too early, so that the line

var1 = DoubleVar

will raise a NameError. The fix is mechanical: run the program, go to the
line with the NameError and add the 'Tkinter.' prefix.

Once you have done that you should take the time to find good variable
names. var1? I have no idea what value that could hold until I've read the
whole program. That's feasible here, but program size may grow over time,
and can you still tell me what var1 means next week? I recommend names that
reflect the problem domain, e. g. `var_dutycycle` or just `dutycycle`.

Next you should consider grouping the code by topic -- not necessarily into
functions; having a section that does the setup for the dutycycle data and
widgets and one for the time etc., visually separated by one or two empty
lines should be sufficient.

If you're ambitious you should read up on the grid layout manager. I allows
widget size to change depending on the window size.

The Text widget can be used to write whole Editors (like IDLE) -- it does no
harm here, but seems a bit heavyweight for just an On/Off display. I would
go with a Label or Entry.

What does a red widget with no text mean, by the way? On, off, or undefined?
Personally, I like to start with a defined state. An easy way to achieve
this is to call

button_off_cmd() # or button_on_cmd()

manually before your program enters the mainloop() -- just like you did with
timer0().

PS: An easy way to get an idea of what a script does is to run it. I'd guess
that by keeping the Rasperry-Pi-specific code in you are reducing the number
of readers who can do that by a few orders of magnitude. I managed to get it
to run with the following ad-hoc changes:

$ diff -u raspberry_orig.py raspberry_mock.py
--- raspberry_orig.py 2014-01-17 16:10:20.843334832 +0100
+++ raspberry_mock.py 2014-01-17 16:10:58.970855503 +0100
@@ -1,7 +1,36 @@
#!/usr/bin/env python
import Tkinter
+from Tkinter import *
import time
-import RPi.GPIO as GPIO
+
+try:
+ import RPi.GPIO as GPIO
+except ImportError:
+ class Name(str):
+ def __repr__(self):
+ return self
+
+ class GPIO:
+ def __init__(self, prefix):
+ self.prefix = prefix
+ def __getattr__(self, name):
+ if name in ["BOARD", "OUT"]:
+ return Name(name)
+ if name == "PWM":
+ return GPIO("PWM")
+ if name == "__call__":
+ def c(*args):
+ print "Initializing {}{}".format(self.prefix, args)
+ return self
+ return c
+ def f(*args):
+ print "Calling {}.{}{}".format(self.prefix, name, args)
+ return f
+
+ GPIO = GPIO("GPIO")
+
+
+
GPIO.setmode(GPIO.BOARD)
GPIO.setup(26,GPIO.OUT)
GPIO.setup(24,GPIO.OUT)







==============================================================================
TOPIC: Python declarative
http://groups.google.com/group/comp.lang.python/t/d3cb0aca7152f06f?hl=en
==============================================================================

== 1 of 2 ==
Date: Fri, Jan 17 2014 6:22 am
From: Francesco Bochicchio


Some time ago I played with Tkinter trying a more declarative way of coding the GUI building part and I come out with this:

top = Tk( 'top' ).add (
Frame( 'frame' ).add (
Pack( side = 'top' ),
Frame ( 'panel1' ).add (
Pack( side='left'),
Label ( 'label', text="Entry 1 : " ),
Entry ( 'entry' )
),
Frame( 'panel2' ).add (
Pack( side='left'),
Label ( 'label', text="Entry 2 : " ),
Entry( 'entry' )
),
Pack( side = 'bottom' ), # packing change
Button( 'button',
text='Click Me' ))
)

top.frame.button["command"] = functools.partial(button_cb, top)
top.realize().mainloop()

which, without changing the underlying plumbing, may also be written this way, which avoid nesting but still looks declarative-ish :

top = Tk( 'top' )
top.add( Frame( 'frame' ) )
top.frame.add (
Pack( side = 'top' ),
Frame ( 'panel1' ),
Frame( 'panel2' ),
Pack( side = 'bottom' ), # packing change
Button( 'button',
text='Click Me',
command = functools.partial(button_cb, top) ) )

top.frame.panel1.add(
Pack( side='left'),
Label ( 'label', text="Entry 1 : " ),
Entry ( 'entry' ) )

top.frame.panel2.add(
Pack( side='left'),
Label ( 'label', text="Entry 1 : " ),
Entry( 'entry' ) )

top.realize().mainloop()


The underlying plumbing for those two examples is just two classes amounting to about fifty lines of code, plus one-liner wrappers for each kind of widgets/geometry

This just to tell you that yes, with python you can write declarative-looking code ... if you don't mind parenthesis :-)




== 2 of 2 ==
Date: Fri, Jan 17 2014 6:47 am
From: sertorbe@gmail.com


El miércoles, 15 de enero de 2014 18:02:08 UTC+1, Sergio Tortosa Benedito escribió:
> Hi I'm developing a sort of language extension for writing GUI programs
>
> called guilang, right now it's written in Lua but I'm considreing Python
>
> instead (because it's more tailored to alone applications). My question
>
> it's if I can achieve this declarative-thing in python. Here's an
>
> example:
>
>
>
> Window "myWindow" {
>
> title="Hello world";
>
> Button "myButton" {
>
> label="I'm a button";
>
> onClick=exit
>
> }
>
> }
>
> print(myWindow.myButton.label)
>
>
>
> Of course it doesn't need to be 100% equal. Thanks in advance
>
>
>
> Sergio

Wow thank you very much, really. I wasn't expecting that much from everyone. BTW, sorry for no answering earlier , I'm receiving no e-mails from the list (I'll look later what happens). First, I don't like that all parenthesis, I like to differentiate which type of delimiter is, this is not so bad if using spaces but anyways it's a little more difficult.Second, In regard, to using something like myWindow=Window rather than Window "myWindow", at first I didn't liked it that much, but in the end it does tell the user that the attributes can be accesed just like anything else. Finally , the project I'm developing (guilang) it's toolkit-independent so I don't mind having to do some wrappers.

Sergio





==============================================================================
TOPIC: python2.6 needed as an aptitude package as dependency
http://groups.google.com/group/comp.lang.python/t/785d1b0f7843ab4c?hl=en
==============================================================================

== 1 of 2 ==
Date: Fri, Jan 17 2014 6:24 am
From: Jan Hapala


Hello,

I need to install a program (MACS: http://liulab.dfci.harvard.edu/MACS/) for which I need to have Python2.6 installed.

I do have two other Pythons installed but not this version.

1) So I tried apt-get install... python2.6 is not there as a package (I am running Linux Mint 15).

2) Okay, I added some repos to the /etc/apt/sources.list:
deb http://packages.linuxmint.com/ debian main upstream import
deb http://debian.linuxmint.com/latest testing main contrib non-free
deb http://debian.linuxmint.com/latest/security testing/updates main contrib non-free
deb http://debian.linuxmint.com/latest/multimedia testing main non-free

I ran apt-get update... python2.6 not there

3) I downloaded python2.6 as a source tar and compiled it and installed with make altinstall...
Python2.6 is installed. When I enter "python" in the command line and hit Tab, I can see there now all three versions of python.

Still I get the same error:
dpkg: dependency problems prevent configuration of macs:
macs depends on python2.6; however:
Package python2.6 is not installed.

I will be grateful for your suggestions,

Jan




== 2 of 2 ==
Date: Fri, Jan 17 2014 6:43 am
From: Chris Angelico


On Sat, Jan 18, 2014 at 1:24 AM, Jan Hapala <jan@hapala.cz> wrote:
> I need to install a program (MACS: http://liulab.dfci.harvard.edu/MACS/) for which I need to have Python2.6 installed.
>
> I do have two other Pythons installed but not this version.

Is one of those Pythons a 2.7? If so, MACS will probably run with
that. The only problem is that the dpkg installer doesn't know that
you have the right dependencies. This isn't a Python question, it's a
Debian packaging one, but I happen to know one of the ways to deal
with this: the 'equivs' system. Since you've now installed Python 2.6
from source, you do have it, so all you need to do is make a dummy
package called (or providing) python2.6.

http://www.debian.org/doc/manuals/apt-howto/ch-helpers.en.html

I used this system at work for several packages where I wanted to run
a newer version of something than the repos provided. Saved us a lot
of hassle.

ChrisA





==============================================================================
TOPIC: Python 3.x adoption
http://groups.google.com/group/comp.lang.python/t/3d5defc6634ef3b4?hl=en
==============================================================================

== 1 of 3 ==
Date: Fri, Jan 17 2014 7:27 am
From: Grant Edwards


On 2014-01-14, Staszek <noreply@eisenbits.com> wrote:

> What's the problem with Python 3.x?

The problem with Python 3.x is Python 2.7. ;)

> What's wrong?...

Python 2.7 still does everything 99% of us need to do, and we're too
lazy to switch.

--
Grant Edwards grant.b.edwards Yow! We have DIFFERENT
at amounts of HAIR --
gmail.com




== 2 of 3 ==
Date: Fri, Jan 17 2014 8:15 am
From: Tim Chase


On 2014-01-17 15:27, Grant Edwards wrote:
> > What's wrong?...
>
> Python 2.7 still does everything 99% of us need to do, and we're too
> lazy to switch.

And in most distros, typing "python" invokes 2.x, and explicitly
typing "python3" is almost 17% longer. We're a lazy bunch! :-)

-tkc








== 3 of 3 ==
Date: Fri, Jan 17 2014 8:21 am
From: Mark Lawrence



On 17/01/2014 16:15, Tim Chase wrote:
> On 2014-01-17 15:27, Grant Edwards wrote:
>>> What's wrong?...
>>
>> Python 2.7 still does everything 99% of us need to do, and we're too
>> lazy to switch.
>
> And in most distros, typing "python" invokes 2.x, and explicitly
> typing "python3" is almost 17% longer. We're a lazy bunch! :-)
>
> -tkc
>

For the really lazy the obvious solution is to switch to Windows where
it's simply "py -2" or "py -3".

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence





==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate