Re: for / while else doesn't make sense

2016-05-21 Thread Erik

On 20/05/16 01:06, Steven D'Aprano wrote:


In my experience, some people (including me) misunderstand "for...else" to
mean that the else block runs if the for block *doesn't*. It took me the
longest time to understand why this didn't work as I expected:

for x in seq:
 pass
else:
 print("seq is empty")


So why don't we consider if that should be a syntax error - "else" 
clause on "for" loop with no "break" in its body? I know that doesn't 
change your fundamental mental model, but it's a hint that it's wrong :)


As it's backwards-incompatible, it could be introduced using a 
__future__ import (a precedent is 'generators' and the "yield" keyword 
back in the day) which those who would like the new check could add to 
the top of their sources.


But also, as you say, any instances of that construct in the wild is 
almost certainly a bug, so it would be good to be able to test code 
using a command-line or similar switch to turn on the behaviour by 
default for testing existing bodies of code.


I notice that pylint complains about this (as a warning). Is there any 
reason why this should _not_ just be considered an error and be done 
with it?


E.
--
https://mail.python.org/mailman/listinfo/python-list


Re: for / while else doesn't make sense

2016-05-21 Thread Chris Angelico
On Sat, May 21, 2016 at 5:20 PM, Erik  wrote:
> On 20/05/16 01:06, Steven D'Aprano wrote:
>
>> In my experience, some people (including me) misunderstand "for...else" to
>> mean that the else block runs if the for block *doesn't*. It took me the
>> longest time to understand why this didn't work as I expected:
>>
>> for x in seq:
>>  pass
>> else:
>>  print("seq is empty")
>
>
> So why don't we consider if that should be a syntax error - "else" clause on
> "for" loop with no "break" in its body? I know that doesn't change your
> fundamental mental model, but it's a hint that it's wrong :)
>
> As it's backwards-incompatible, it could be introduced using a __future__
> import (a precedent is 'generators' and the "yield" keyword back in the day)
> which those who would like the new check could add to the top of their
> sources.
>
> But also, as you say, any instances of that construct in the wild is almost
> certainly a bug, so it would be good to be able to test code using a
> command-line or similar switch to turn on the behaviour by default for
> testing existing bodies of code.
>
> I notice that pylint complains about this (as a warning). Is there any
> reason why this should _not_ just be considered an error and be done with
> it?

Because it's not the language parser's job to decide what's "sensible"
and what's "not sensible". That's a linter's job. Some things
fundamentally can't work, but others work fine and might just be
not-very-useful - for example:

def f(x):
x if x <= 2 else x * f(x-1)

This is syntactically-legal Python code, but it probably isn't doing
what you want it to (in Python, a bare final expression does NOT
become the function's return value, although that does happen in other
languages). A linter should look at this and give a warning (even if
the else part has side effects, the first part can't, and the
condition shouldn't), but the language will happily evaluate it (this
example from CPython 3.6):

>>> dis.dis(f)
  2   0 LOAD_FAST0 (x)
  3 LOAD_CONST   1 (2)
  6 COMPARE_OP   1 (<=)
  9 POP_JUMP_IF_FALSE   18
 12 LOAD_FAST0 (x)
 15 JUMP_FORWARD17 (to 35)
>>   18 LOAD_FAST0 (x)
 21 LOAD_GLOBAL  0 (f)
 24 LOAD_FAST0 (x)
 27 LOAD_CONST   2 (1)
 30 BINARY_SUBTRACT
 31 CALL_FUNCTION1 (1 positional, 0 keyword pair)
 34 BINARY_MULTIPLY
>>   35 POP_TOP
 36 LOAD_CONST   0 (None)
 39 RETURN_VALUE

So, yes, this function might load up the value of x (position 12),
then jump to 35 and discard that value, before unconditionally
returning None. Not a problem. It's up to the linter, and ONLY the
linter, to tell you about this.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to memory dump an object?

2016-05-21 Thread jfong
Make a quick experiment under version 3.4.4 through this simple "tool" Chris 
had provided, now I know how the unicode string was stored in memory:-)

>>> s1 = '\x80abc'
>>> s1
'\x80abc'
>>> len(s1)
4
>>> sys.getsizeof(s1)
41
>>> s1ptr = ctypes.cast(id(s1), ctypes.POINTER(ctypes.c_uint8))
>>> bytes([s1ptr[i] for i in range(41)])
b'\x01\x00\x00\x00\xe8\xa5g^\x04\x00\x00\x00\x04\xff\x04&\xa4\x00\x00d\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80abc\x00'
>>>
# a simple unicode string, each code point can be stored in one byte

>>> s2 = '\u0080abc'
>>> s2
'\x80abc'
>>> len(s2)
4
>>> sys.getsizeof(s2)
41
>>> s2ptr = ctypes.cast(id(s2), ctypes.POINTER(ctypes.c_uint8))
>>> bytes([s2ptr[i] for i in range(41)])
b'\x01\x00\x00\x00\xe8\xa5g^\x04\x00\x00\x00\x04\xff\x04&\xa4\x00\x00|\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80abc\x00'
>>>
# Python change it automatically to store each code point into one byte

>>> s3 = '\u07b4abc'
>>> s3
'\u07b4abc'
>>> len(s3)
4
>>> sys.getsizeof(s3)
46
>>> s3ptr = ctypes.cast(id(s3), ctypes.POINTER(ctypes.c_uint8))
>>> bytes([s3ptr[i] for i in range(46)])
b'\x01\x00\x00\x00\xe8\xa5g^\x04\x00\x00\x00\x19n\x93]\xa8\x00\x00dd\r\x1d\x02\x
00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\xb4\x07a\x00b\x00c\x00\x00\x00'
>>>
# use two bytes to store each code point, even the end-of-string mark

>>> s4 = '\U00025049abc'
>>> s4
'\U00025049abc'
>>> len(s4)
4
>>> sys.getsizeof(s4)
56
>>> s4ptr = ctypes.cast(id(s4), ctypes.POINTER(ctypes.c_uint8))
>>> bytes([s4ptr[i] for i in range(56)])
b'\x01\x00\x00\x00\xe8\xa5g^\x04\x00\x00\x003\xdd\xa7"\xb0\x00\x00\x00\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00IP\x02\x00a\x00\x00\x00b\x
00\x00\x00c\x00\x00\x00\x00\x00\x00\x00'
>>>
# use four bytes to store each code point

--Jach
-- 
https://mail.python.org/mailman/listinfo/python-list


problem regarding installation

2016-05-21 Thread bhagyadhar sahoo
i have downloaded the software from your site..
but while installing it shows some problem ..
plz help me out..or let me know how can i get the solution,.. i am waiting
for ur replay

thanks
bhagya
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for / while else doesn't make sense

2016-05-21 Thread Marko Rauhamaa
Erik :

> On 20/05/16 01:06, Steven D'Aprano wrote:
>> In my experience, some people (including me) misunderstand
>> "for...else" to mean that the else block runs if the for block
>> *doesn't*. It took me the longest time to understand why this didn't
>> work as I expected:
>>
>> for x in seq:
>>  pass
>> else:
>>  print("seq is empty")
>
> So why don't we consider if that should be a syntax error - "else"
> clause on "for" loop with no "break" in its body? I know that doesn't
> change your fundamental mental model, but it's a hint that it's wrong
> :)

While we are at it, we should trigger a syntax error in these cases:

   a = 0
   b += a # pointless to add a 0

   c = 1
   d *= c # pointless to multiply by 1

   if False:  # pointless to test for truth in falsity
   ...

However, all of these "pointless" constructs crop up in real situations,
and artifically flagging them as errors would lead to unnecessary
frustration.

For example,

   if False:
   yield None

is the way to create a generator that doesn't generate any output.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem regarding installation

2016-05-21 Thread mm0fmf

On 21/05/2016 08:55, bhagyadhar sahoo wrote:

i have downloaded the software from your site..
but while installing it shows some problem ..
plz help me out..or let me know how can i get the solution,.. i am waiting
for ur replay

thanks
bhagya


We don't know which web site you are talking about.
We don't know which software you are talking about.
We don't know what operating system you are using.
We don't know what the problem was.

How can we help you if you don't explain the problem in some detail?
--
https://mail.python.org/mailman/listinfo/python-list


Re: problem regarding installation

2016-05-21 Thread Peter Otten
bhagyadhar sahoo wrote:

> i have downloaded the software from your site..
> but while installing it shows some problem ..
> plz help me out..or let me know how can i get the solution,.. i am waiting
> for ur replay

We are sorry, your operating system is no longer supported by current 
versions of Python. 

Try Python 3.4.3.

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


Re: problem regarding installation

2016-05-21 Thread Chris Angelico
On Sat, May 21, 2016 at 7:14 PM, Peter Otten <__pete...@web.de> wrote:
> bhagyadhar sahoo wrote:
>
>> i have downloaded the software from your site..
>> but while installing it shows some problem ..
>> plz help me out..or let me know how can i get the solution,.. i am waiting
>> for ur replay
>
> We are sorry, your operating system is no longer supported by current
> versions of Python.
>
> Try Python 3.4.3.

Or try a better operating system.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for / while else doesn't make sense

2016-05-21 Thread Steven D'Aprano
On Sat, 21 May 2016 02:01 pm, Chris Angelico wrote:

> On Sat, May 21, 2016 at 1:50 PM, Steven D'Aprano 
> wrote:

>> Would you classify the second line here:
>>
>> print("Hello World!")
>> pass
>>
>>
>> as a bug? What exactly would your bug report be? "pass statement does
>> nothing, as expected. It should do nothing. Please fix."
>>
> 
> Yes, I would. It's not a bug in Python or CPython - it's a bug in the
> second line of code there. It implies something that isn't the case.

What do you think it implies?

What part of the docs for "pass" implies this thing?

help("pass"):

``pass`` is a null operation --- when it is executed, nothing 
happens. It is useful as a placeholder when a statement is 
required syntactically, but no code needs to be executed, for 
example:  [examples snipped]



> It's like having this code:
> 
> if True:
> pass
> elif False:
> pass
> else:
> assert True

Hmmm. Well, let see:


py> if True:
... pass
... elif False:
... pass
... else:
... assert True
...
Traceback (most recent call last):
  File "", line 6, in 
AssertionError


What witchcraft is this?

S
P
O
I
L
E
R
 
S
P
A
C
E

I'm running Python 2, and have redefined True = False.

But even in Python 3, what exactly is the bug supposed to be? The Python 3
compiler, as naive and simple as it is, is perfectly capable of compiling
out the dead code:

py> dis.dis("""if True: pass
... elif False: pass
... else: assert True
... """)
  1   0 LOAD_CONST   0 (None)
  3 RETURN_VALUE


So the worst we can say about this is that it is pointless dead code.


> It's well-defined code. You know exactly what Python should do. But is
> it good code, 

Well, it's not *great* code, that's for sure. Is it good code? That depends.
There are certainly semantic differences between Python 2 and 3, and
without knowing the intention of the author (that would be you) its hard to
say exactly what the code should be. But it's *legal* code that does
exactly what the language documentation says it ought to do. 


> or is it the sort of thing that gets posted here: 
> 
> http://thedailywtf.com/articles/a-spiritual-journey

I'm not sure how that specific Daily-WTF article is relevant.

But in general, is it worthy of Daily-WTF? No, I don't think so. I think
that your "True, False" example could do with some refactoring and cleanup:
perhaps it is dead code that should be completely removed, but that's not
necessarily Daily-WTF worthy. Or it's some part of some sort of Python 2+3
compatibility layer intending to detect rebindings to True or False, in
which case it is certainly ugly (and probably buggy) but may be needed.

As far as my example, using "pass" in the code... no, it's not WTF-worthy
either. It's at worst worth a raised eyebrow. Without knowing the context
of where it came from, it isn't even clear that it is pointless code.
Perhaps it is from a test suite checking that `pass` is correctly parsed,
compiled and executed as a do-nothing statement.



-- 
Steven

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


PyData EuroPython 2016

2016-05-21 Thread M.-A. Lemburg
We are excited to announce a complete PyData (http://pydata.org/)
track at EuroPython 2016 in Bilbao, Basque Country, Spain, from July
14-24.

*** PyData EuroPython 2016 ***

https://ep2016.europython.eu/en/events/pydata/


The PyData track will be part of the EuroPython 2016 conference, so
you won’t need to buy extra tickets to join.

We will have more than 30 talks, 5 training and 2 poster sessions
dedicated to PyData on Thursday 21st and Friday 22nd of July.

If you’d like to attend the PyData EuroPython 2016 track, please
register for EuroPython 2016 soon.

https://ep2016.europython.eu/en/registration/

With gravitational regards,
--
EuroPython 2016 Team
http://ep2016.europython.eu/
http://www.europython-society.org/

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


Re: for / while else doesn't make sense

2016-05-21 Thread Chris Angelico
On Sat, May 21, 2016 at 7:56 PM, Steven D'Aprano  wrote:
> On Sat, 21 May 2016 02:01 pm, Chris Angelico wrote:
>
>> On Sat, May 21, 2016 at 1:50 PM, Steven D'Aprano 
>> wrote:
>
>>> Would you classify the second line here:
>>>
>>> print("Hello World!")
>>> pass
>>>
>>>
>>> as a bug? What exactly would your bug report be? "pass statement does
>>> nothing, as expected. It should do nothing. Please fix."
>>>
>>
>> Yes, I would. It's not a bug in Python or CPython - it's a bug in the
>> second line of code there. It implies something that isn't the case.
>
> What do you think it implies?
>
> What part of the docs for "pass" implies this thing?
>
> help("pass"):
>
> ``pass`` is a null operation --- when it is executed, nothing
> happens. It is useful as a placeholder when a statement is
> required syntactically, but no code needs to be executed, for
> example:  [examples snipped]

So why is a statement required syntactically after that print call?
Surely that implies something about the programmer's intent? It
certainly isn't required according to the code you've shown me; and if
someone submitted this code to me, I'd query it ("was there something
else meant to be here?").

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Education [was Re: for / while else doesn't make sense]

2016-05-21 Thread Steven D'Aprano
On Sat, 21 May 2016 03:18 pm, Rustom Mody wrote:

> Given that for the most part, most of us are horribly uneducated [
>
http://www.creativitypost.com/education/9_elephants_in_the_classroom_that_should_unsettle_us
> ]
> how do we go about correcting our wrong primacies?


An interesting article, but very US-centric. 

Nevertheless, let's not forget that the general school system is designed to
churn out more-or-less identical workers capable of pulling the levers on
late 19th and early 20th century machines for their bosses. The fact that
it does more than that, even if badly, is a bonus.


-- 
Steven

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


Re: for / while else doesn't make sense

2016-05-21 Thread Steven D'Aprano
On Sat, 21 May 2016 05:20 pm, Erik wrote:

> On 20/05/16 01:06, Steven D'Aprano wrote:
> 
>> In my experience, some people (including me) misunderstand "for...else"
>> to mean that the else block runs if the for block *doesn't*. It took me
>> the longest time to understand why this didn't work as I expected:
>>
>> for x in seq:
>>  pass
>> else:
>>  print("seq is empty")
> 
> So why don't we consider if that should be a syntax error - "else"
> clause on "for" loop with no "break" in its body? I know that doesn't
> change your fundamental mental model, but it's a hint that it's wrong :)

Just for the record, that's not my mental model *now*.

It took me a long time to work out what for...else was actually doing, but
some years ago I finally managed to do so. It's my argument that had the
keyword been "then" (implying that the `then` block is unconditionally
executed after the `for` block, which is the actual behaviour of the
interpreter) rather than "else" implying that it is an alternative to the
`for` block) I wouldn't have come up with the wrong mental model in the
first place. And I'm not the only one who has come up with the same, wrong,
model.

But you do ask a good question. Why isn't for...else with no break a syntax
error? I suppose it could be. But that's a *stylistic* question, and Python
generally treats that as "none of the compiler's business". It's not the
business of the compiler to enforce good code, only legal code. We can
legally write lots of code of questionable value:

while 0:
print("surprise!")

n = 1 + int(x) - 1

x = x

try:
something()
finally:
pass


without the compiler judging us and making it a syntax error. Why should
for...else be any different? The behaviour is perfectly well defined:

- first the `for` block runs, as many times as needed;
- then the `else` block runs, once.


Of course, the usual four keywords (continue, break, return, raise) will
change the order of execution by jumping to:

- the top of the for loop;
- past the for...else blocks;
- out of the current function;
- the nearest exception handler

respectively. But in the absence of a jump, for...else works as specified,
regardless of whether there is a break in it or not.


> As it's backwards-incompatible, it could be introduced using a
> __future__ import (a precedent is 'generators' and the "yield" keyword
> back in the day) which those who would like the new check could add to
> the top of their sources.

Sure, we *could* do this, but as I said, it does go against the usual
philosophy that the compiler shouldn't make judgements on what is good code
and what isn't. 


> But also, as you say, any instances of that construct in the wild is
> almost certainly a bug, 

I don't think it was me calling it a bug.


> so it would be good to be able to test code
> using a command-line or similar switch to turn on the behaviour by
> default for testing existing bodies of code.

I think that switch is called "use Pylint, PyChecker, Jedi or some other
opinionated linter or style-checker".

 
> I notice that pylint complains about this (as a warning). Is there any
> reason why this should _not_ just be considered an error and be done
> with it?

Because there's nothing actually broken with it.

There's lots of code which a human programmer would recognise as "silly",
or "wrong", but is well-defined and legal. Just because you can't think of
a reason to do something doesn't mean it should be prohibited.



-- 
Steven

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


Re: for / while else doesn't make sense

2016-05-21 Thread Steven D'Aprano
On Sat, 21 May 2016 08:08 pm, Chris Angelico wrote:

> On Sat, May 21, 2016 at 7:56 PM, Steven D'Aprano 
> wrote:
>> On Sat, 21 May 2016 02:01 pm, Chris Angelico wrote:
>>
>>> On Sat, May 21, 2016 at 1:50 PM, Steven D'Aprano 
>>> wrote:
>>
 Would you classify the second line here:

 print("Hello World!")
 pass


 as a bug? What exactly would your bug report be? "pass statement does
 nothing, as expected. It should do nothing. Please fix."

>>>
>>> Yes, I would. It's not a bug in Python or CPython - it's a bug in the
>>> second line of code there. It implies something that isn't the case.
>>
>> What do you think it implies?
>>
>> What part of the docs for "pass" implies this thing?
>>
>> help("pass"):
>>
>> ``pass`` is a null operation --- when it is executed, nothing
>> happens. It is useful as a placeholder when a statement is
>> required syntactically, but no code needs to be executed, for
>> example:  [examples snipped]
> 
> So why is a statement required syntactically after that print call?

Who said it was required?

The docs say that `pass` is useful when a statement is required, not the
other way: you can put `pass` anywhere a statement can go, without it being
required.


> Surely that implies something about the programmer's intent? It
> certainly isn't required according to the code you've shown me; and if
> someone submitted this code to me, I'd query it ("was there something
> else meant to be here?").

Sure. Does that make it a bug? I don't think so. I think that a linter
should flag it as unnecessary code, but the compiler certainly shouldn't
prohibit it. And a human reviewer might be able to judge whether it belongs
or not.

Some people might not like "FIXME" or "XXX" comments to flag missing code,
and use `pass` statements as placeholders. Who are we to tell them they
shouldn't?

I think we agree that it's not the compiler's job to enforce good coding
standards.




-- 
Steven

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


Re: for / while else doesn't make sense

2016-05-21 Thread Chris Angelico
On Sat, May 21, 2016 at 8:55 PM, Steven D'Aprano  wrote:
> I think we agree that it's not the compiler's job to enforce good coding
> standards.

Yep. I believe we are in (possibly belligerent) agreement.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for / while else doesn't make sense

2016-05-21 Thread Steven D'Aprano
On Sat, 21 May 2016 04:03 pm, Marko Rauhamaa wrote:

> theh...@gmail.com:
> 
>> You seem to have missed the point. Nobody is suggesting, I don't
>> believe, that all of a language should be intuitive. Rather that if
>> any part of it is unnecessarily counter-intuitive, it may be worth
>> looking for a better solution. Python is a very well designed language
>> when it comes to in linguistic presentation. In this case however, it
>> is not only unintuitive but counter-intuitive.
> 
> The for-else construct is a highly practical feature. It is in no way
> inherently counter-intuitive. As any new thing, it needs to be learned
> and used to be appreciated.

Yes, this!

I might have issues with the keyword chosen, but the feature itself is very
clever.

Does anyone know of other languages that include the same feature? It's very
rare for Python to innovate in language features.

(I wonder if it came from ABC?)





-- 
Steven

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


Re: for / while else doesn't make sense

2016-05-21 Thread Steven D'Aprano
On Sat, 21 May 2016 09:57 am, Dennis Lee Bieber wrote:

> On Fri, 20 May 2016 11:55:34 - (UTC), Jon Ribbens
>  declaimed the following:
> 
>>
>>I would find that very confusing. "then:" makes it sound like
>>executing that block is the usual case, when in practice it is
>>usually the exception - the fallback code if the expected value
>>was not found.
> 
> And I'll second that...
> 
> In those languages that use "then" as a keyword, it separates the "if"
> conditional from the "true" block of code. Or -- visualize replacing the
> ":" on the "for" with the word "then"
> 
> for x in sequence then
> do stuff with x
> else
> do something with no x
> 
> 
> If a different keyword is to be introduced, I nominate "otherwise"

"otherwise" fails for the same reason that "else" fails: it suggests that
the else block is an alternative to the for block, which is exactly what it
is NOT.




-- 
Steven

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


Re: How do I subclass the @property setter method?

2016-05-21 Thread Dirk Bächle

Hi Christopher,

On 20.05.2016 20:50, Christopher Reimer wrote:

Greetings,

My chess engine has a Piece class with the following methods that use
the @property decorator to read and write the position value.



slightly off topic: is your chess engine available in a public repo somewhere? I think I've started to implement something similar 
(display of chess boards and wrapping different chess engines), so I'd like to have a look. ;)


Best regards,

Dirk


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


Re: for / while else doesn't make sense

2016-05-21 Thread Ian Kelly
On Sat, May 21, 2016 at 5:26 AM, Steven D'Aprano  wrote:
> Does anyone know of other languages that include the same feature? It's very
> rare for Python to innovate in language features.
>
> (I wonder if it came from ABC?)

According to Raymond Hettinger starting at about 15:50 in this video:

http://pyvideo.org/video/1780/transforming-code-into-beautiful-idiomatic-pytho

It was invented by Donald Knuth (including the choice of keyword).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for / while else doesn't make sense

2016-05-21 Thread Grant Edwards
On 2016-05-21, Ian Kelly  wrote:
> On Sat, May 21, 2016 at 5:26 AM, Steven D'Aprano  wrote:
>
>> Does anyone know of other languages that include the same feature?
>> It's very rare for Python to innovate in language features.
>>
>> (I wonder if it came from ABC?)
>
> According to Raymond Hettinger starting at about 15:50 in this
> video:
>
> http://pyvideo.org/video/1780/transforming-code-into-beautiful-idiomatic-pytho
>
> It was invented by Donald Knuth (including the choice of keyword).

If true, that alone dismisses with prejudice any question of changing it.

As if backwards compatibility weren't a compelling enough argument.

Besides which, I happen to think it makes sense the way it is.

[I haven't been paying very close attention to this thread for a
while, so I assume that "this feature" and "it" still refer to having
an else clause in for/while loops?]

I can't count the number of times I've wished C had such a feature,
and have sometimes resorted to using a "goto" to get the same
semantics in an easy to read/understand way.

--
Grant

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


Image loading problem

2016-05-21 Thread sweating_...@yahoo.com
Hi All,


I am working on an image project, and I can display my image in main(). I mean, 
I can load my image in my main(). Needless, it is awkward. I am trying to load 
my image with a function, but got an empty image window popped up, no image 
content loaded. Please take a look at code:



rom Tkinter import *

def load_img(win):  
img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()

win = Tk()
load_img(win)
win.mainloop()

Somebody can help me out? Thanks!

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


Re: How do I subclass the @property setter method?

2016-05-21 Thread Christopher Reimer



On 5/21/2016 1:52 AM, Dirk Bächle wrote:

Hi Christopher,

On 20.05.2016 20:50, Christopher Reimer wrote:

Greetings,

My chess engine has a Piece class with the following methods that use
the @property decorator to read and write the position value.



slightly off topic: is your chess engine available in a public repo
somewhere? I think I've started to implement something similar (display
of chess boards and wrapping different chess engines), so I'd like to
have a look. ;)


Not at this time. I'll send a post to the list when I make the code 
available. My chess engine doesn't do much beyond displaying a text-only 
board. Since a chess engine presents an unlimited number of programming 
challenges, I'm using it to learn the finer points of Python.


Thank you,

Chris R.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Education [was Re: for / while else doesn't make sense]

2016-05-21 Thread Christopher Reimer

On 5/21/2016 3:05 AM, Steven D'Aprano wrote:

On Sat, 21 May 2016 03:18 pm, Rustom Mody wrote:


Given that for the most part, most of us are horribly uneducated [


http://www.creativitypost.com/education/9_elephants_in_the_classroom_that_should_unsettle_us

]
how do we go about correcting our wrong primacies?



An interesting article, but very US-centric.

Nevertheless, let's not forget that the general school system is designed to
churn out more-or-less identical workers capable of pulling the levers on
late 19th and early 20th century machines for their bosses. The fact that
it does more than that, even if badly, is a bonus.


Under various proposals in the U.S., everyone will soon learn how to 
program and/or become a computer scientist. Won't be long before some 
snotty-nosed brat graduates from preschool, takes a look at your code, 
and poops in his diapers. He will then dips his finger into his diaper, 
write on the whiteboard how your code can be written in a single line, 
and summary dismiss you with security escorting you off the premises.


Gotta love the future. :)

Thank you,

Chris R.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Image loading problem

2016-05-21 Thread Peter Otten
sweating_...@yahoo.com wrote:

> I am working on an image project, and I can display my image in main(). I 
mean, I can load my image in my main(). Needless, it is awkward. I am trying 
to load my image with a function, but got an empty image window popped up, 
no image content loaded. Please take a look at code:
> 
> 
> 
> rom Tkinter import *
> 
> def load_img(win):  
> img = PhotoImage(file="xxx.gif")
> Label(win, image=img).pack()
> 
> win = Tk()
> load_img(win)
> win.mainloop()
> 
> Somebody can help me out? Thanks!

It's not your fault, there's an odd quirk in the library: you have to keep a 
reference of the PhotoImage instance around to prevent the image from being 
garbage-collected. For example

from Tkinter import *

def load_img(win):
global img

img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()

win = Tk()
load_img(win)
win.mainloop()

will work because img is now a global that is not deleted until the script 
ends (but don't run the function twice -- then the first image will 
disappear).

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


Re: Education [was Re: for / while else doesn't make sense]

2016-05-21 Thread Marko Rauhamaa
Christopher Reimer :

> Under various proposals in the U.S., everyone will soon learn how to
> program and/or become a computer scientist. Won't be long before some
> snotty-nosed brat graduates from preschool, takes a look at your code,
> and poops in his diapers. He will then dips his finger into his
> diaper, write on the whiteboard how your code can be written in a
> single line, and summary dismiss you with security escorting you off
> the premises.
>
> Gotta love the future. :)

Unfortunately, most CS graduates don't seem to know how to program.

Yes, some highschoolers could excel in the post of a senior software
engineer -- I've had the privilege of working alongside several
specimens. However, it has been known for half a century that good
developers are hard to come by.

I think it is essential to learn the principles of programming just like
it is essential to learn the overall principles of nuclear fission or be
able to locate China on the map. However, a small minority of humanity
will ever earn a living writing code.

At the same time, it may be that in the not-too-distant future, the
*only* jobs available will be coding jobs as we start to take the
finishing steps of automating all manufacturing, transportation and
services. Then, we will have a smallish class of overworked coders who
have no use or time for money and vast masses of jobless party-goers who
enjoy the fruits of the coders' labor.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Image loading problem

2016-05-21 Thread Peter Pearson
On Sat, 21 May 2016 08:22:41 -0700 (PDT), sweating_...@yahoo.com wrote:
>
> I am working on an image project, and I can display my image in
> main(). I mean, I can load my image in my main(). Needless, it is
> awkward. I am trying to load my image with a function, but got an
> empty image window popped up, no image content loaded. Please take a
> look at code:
>
> rom Tkinter import *
>
> def load_img(win):
>   img = PhotoImage(file="xxx.gif")
>   Label(win, image=img).pack()
>   
> win = Tk()
> load_img(win)
> win.mainloop()
>

This seems to work:
---
from Tkinter import Tk, PhotoImage, Label

def load_img(win):
img = PhotoImage(file="/home/peter/dow.gif")
Label(win, image=img).pack()
return img

win = Tk()
img = load_img(win)
win.mainloop()
---

I guess the problem was that the "img" created in load_img went
out of scope and was deleted when load_img returned.  I just tried
the "return img" as an experiment to keep it from going out of scope;
from a software-engineering standpoint this might be a gross kluge.

Baffling? Personally, I never got past feeling generally bewildered in
Tkinter-land, and now I use matplotlib for all my graphical needs.  I
had great hopes for PyGUI at one point, but I hear very little about it
now.

-- 
To email me, substitute nowhere->runbox, invalid->com.
-- 
https://mail.python.org/mailman/listinfo/python-list


Python and GPSD

2016-05-21 Thread John McKenzie

 Good day, all.

 I need help using the Python bindings for GPSD. Specifically, I would 
like to take a latitude reading, put it in a variable and use it later. 
The problem is that every example I see involves constantly taking 
changing readings. That part I have working for myself by following 
existing examples.

 If I put any code in any kind of loop my latitude variable will keep 
changing. If I do not put in a loop, it will appear to be zero. (I do  
not live on the equator.)

 The Python GPS module is installed, cgps works fine, other aspects of 
the script involving GPS work fine.

 I want to be able to turn on a single board computing device, have it  
get a latitude reading, put that coordinate into a variable, then go 
along its merry way using that variable for the rest of the script. 
(Running my script upon boot, running the GPSD service, etc, is all fine 
and working.)

My script:
http://hastebin.com/zuwamuqoxe.coffee

 On line 37 I try to define an initial latitude variable, intLatitude. It 
comes up as zero right now. I need it to be whatever the GPS says for 
latitude when the script starts and stay that way.

 Help is appreciated.

 Apologies to those who read my script for the poor code quality. Learned 
a little Python last year, then only started again with it recently. 
Still a Python newbie, and am rushed for this particular project.

 Thanks.

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


Re: Image loading problem

2016-05-21 Thread Gary Herron

On 05/21/2016 08:22 AM, sweating_...@yahoo.com wrote:

Hi All,


I am working on an image project, and I can display my image in main(). I mean, 
I can load my image in my main(). Needless, it is awkward. I am trying to load 
my image with a function, but got an empty image window popped up, no image 
content loaded. Please take a look at code:



rom Tkinter import *

def load_img(win):  
img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()

win = Tk()
load_img(win)
win.mainloop()

Somebody can help me out? Thanks!



I believe this the problem (However It's been long since I used Tkinter, 
so be warned ... ):


The function load_img creates a local variable named img which goes out 
of scope and is deleted immediately when the function returns. However, 
Tkinter needs you to keep that image around as long as the Label uses 
it.   So, some solutions are:


keep_me = [] #  Global for keeping references to images
def load_img(win):
img = PhotoImage(file="xxx.gif")
keep_me.append(img)
Label(win, image=img).pack()

or


def load_img(win):
img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()
return img

saved_img = load_img(win)
...


Gary Herron



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

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


Re: Image loading problem

2016-05-21 Thread Terry Reedy

On 5/21/2016 12:54 PM, Peter Otten wrote:

sweating_...@yahoo.com wrote:


I am working on an image project, and I can display my image in main(). I

mean, I can load my image in my main(). Needless, it is awkward. I am trying
to load my image with a function, but got an empty image window popped up,
no image content loaded. Please take a look at code:




rom Tkinter import *

def load_img(win):
img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()

win = Tk()
load_img(win)
win.mainloop()

Somebody can help me out? Thanks!


It's not your fault, there's an odd quirk in the library: you have to keep a
reference of the PhotoImage instance around to prevent the image from being
garbage-collected. For example

from Tkinter import *

def load_img(win):
global img

img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()

win = Tk()
load_img(win)
win.mainloop()

will work because img is now a global that is not deleted until the script
ends (but don't run the function twice -- then the first image will
disappear).


The usual procedure is to create an App class and make images attributes 
of the App instance.  Then load_img would be a method and the first line 
would be 'self.img = ...'.  One can also have a list of images, to use 
in a slide show, or a dict of images, so users can select.


--
Terry Jan Reedy

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


Re: Image loading problem

2016-05-21 Thread Random832
On Sat, May 21, 2016, at 12:54, Peter Otten wrote:
> It's not your fault, there's an odd quirk in the library: you have to
> keep a reference of the PhotoImage instance around to prevent the
> image from being garbage-collected.

Just out of curiosity, why is this a "quirk" and not a bug? Why isn't
the reference held by the Label?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for / while else doesn't make sense

2016-05-21 Thread Erik

On 21/05/16 11:39, Steven D'Aprano wrote:

Just for the record, that's not my mental model *now*.


Sure. And I should have written "one's mental model" - the model of 
anyone writing that code (not you personally) who thought the same at 
the time.



It took me a long time to work out what for...else was actually doing, but
some years ago I finally managed to do so.


Coming from a partly assembler background, I happened to get it straight 
away just because the thought of separate jump targets for the loop 
condition being satisfied and breaking out of the loop being different 
was quite natural (and a very nice feature to have in a high level 
language!).



But you do ask a good question. Why isn't for...else with no break a syntax
error? I suppose it could be. But that's a *stylistic* question, and Python
generally treats that as "none of the compiler's business". It's not the
business of the compiler to enforce good code, only legal code.


On 21/05/16 08:29, Chris Angelico wrote:
> It's up to the linter, and ONLY the linter, to tell you about this.

Apologies for joining two threads here, but my reply is the same to 
both, so it makes sense to me.



Let me tell you a story ;)  Back in the mid-to-late 
1980s I worked with C compilers on hardware that could take several 
minutes to compile even a fairly trivial program. They errored on 
syntactically incorrect code and happily compiled syntactically correct 
code. Sometimes the output of the compiler wouldn't execute as expected 
because of "undefined behaviour" of some parts of the language (which 
the compilers could quite legally accept but would not produce valid 
code for - even illegal ops are fair game at that point). They would 
create valid code for the valid syntax of buggy code ("if (x = y) { 
foo(); }") without a whimper.


At that time, we had a program called 'lint'. Every so often we might 
run it on our sources and find all sorts of questionable behaviour that 
our code might have that we should look harder at (such as that above). 
We didn't run it all the time because it took so much longer to run than 
the compiler itself.


Over time, some compilers started adding the checks and advisories that 
"lint" gave to their messages. For some branded compilers ("Green 
Hills", "SAS/C"), this even became a selling point. They started to do 
this while still retaining the original compilation speed.


Things got faster, more was added to the compiler, and once the compiler 
started to do everything it did and more, lint died(*).




And now, today, the compilers all do far more than the original 'lint' 
program did in almost zero time every time some source is compiled. It 
is free; it is not something one has to remember to run every so often.





So, back to Python ;)

The responses of "we can all write suspect/bad/ineffectual code - so 
just run the linter" takes me back those 30 years to when we HAD to do 
that with our C code too ...


There must be a better way.

I realise that Python has the issue that sometimes the person doing the 
compilation is the end user (by virtue of them executing a .py file), so 
lint-style compiler warnings aren't really appropriate - and that's the 
reason why I suggested a syntax error: I understand that it's not really 
any such thing, but it's all I had to work with and it ensured such code 
could not get as far as the end user.



So I guess my question is perhaps whether Python compilers should start 
to go down the same path that C compilers did 30 years ago (by starting 
to include some linter functionality) but in a way that only outputs the 
messages to developers and not end users. Also, the current "pylint" 
blurs the edges between style (identifier names) and questionable code 
("for/else" with no "break").




E. <-- waiting to be shot down again.



(*) Though to be fair, there are now even more deeply checking 
(commercial) static tools available, which effectively fill the gap that 
'lint' used to.

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


Re: for / while else doesn't make sense

2016-05-21 Thread Michael Selik
On Sat, May 21, 2016, 4:52 PM Erik  wrote:

> So I guess my question is perhaps whether Python compilers should start
> to go down the same path that C compilers did 30 years ago (by starting
> to include some linter functionality)
>

Well, there's that whole optional type hints thing. You should be asking
how to preserve Python's simplicity while adding more static analysis
features.

>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for / while else doesn't make sense

2016-05-21 Thread Steven D'Aprano
On Sun, 22 May 2016 06:48 am, Erik wrote:

> Let me tell you a story ;)  Back in the mid-to-late
> 1980s I worked with C compilers on hardware that could take several
> minutes to compile even a fairly trivial program. They errored on
> syntactically incorrect code and happily compiled syntactically correct
> code. Sometimes the output of the compiler wouldn't execute as expected
> because of "undefined behaviour" of some parts of the language (which
> the compilers could quite legally accept but would not produce valid
> code for - even illegal ops are fair game at that point). They would
> create valid code for the valid syntax of buggy code ("if (x = y) {
> foo(); }") without a whimper.

Don't get me started about C and undefined behaviour.

Fortunately, Python has nothing even remotely like C undefined behaviour.


> At that time, we had a program called 'lint'.
[...]
> And now, today, the compilers all do far more than the original 'lint'
> program did in almost zero time every time some source is compiled. It
> is free; it is not something one has to remember to run every so often. 

This is certainly not the case for Python. With C, you run your
compiler+linter once, and it builds an executable which can then run
without the compiler or linter.

With Python, *every time you run* the code, the compiler runs. The compiler
is the interpreter. It can, sometimes, skip some of the compilation steps
(parsing of source code) by use of cached byte-code files, but not all of
them. Including a linter will increase the size of the compiler
significantly, which much be distributed or installed for even the smallest
Python script, and it will have runtime implications re compilation time,
execution time, and memory use.

If you make the linter optional, say, a Python module that you install
separately and run only if you choose, then you have the status quo.


> So, back to Python ;)
> 
> The responses of "we can all write suspect/bad/ineffectual code - so
> just run the linter" takes me back those 30 years to when we HAD to do
> that with our C code too ...
> 
> There must be a better way.

Yes. And the better way is... don't write a language where you NEED a linter
because the language specification is so fecking *insane* that no human
being can reliably write correct code without running into undefined
behaviour which *can and will* have effects that propagate in both
directions, contaminating code which is correct in unpredictible ways.

https://blogs.msdn.microsoft.com/oldnewthing/20140627-00/?p=633/

One difference between C and Python is that most of the things which Python
linters look at don't actually have implications for correctness. Here are
a few of the features that Pylint looks at:

* line length;
* variable naming standards;
* unused imports;
* unnecessary semi-colons;
* use of deprecated modules;

and a complete list here:

http://pylint-messages.wikidot.com/all-codes

As you can see, most of the actual errors Pylint will pick up would result
in a runtime error, e,g, opening a file with an invalid mode. Most codes
are for code quality issues, related to maintenance issues, not bug
detection.

Coming back to for...else with no break, the behaviour is perfectly
well-defined, and does exactly what it is documented as doing. It's hard to
see that it is a "bug" for something to do what exactly what it is designed
to do. If somebody, for their own idiosyncratic reasons, wants to write:

for x in seq:
spam()
else:
eggs()

(Note: I've done this -- see below.)

and the language insists on a break, they will just pointlessly defeat the
compiler:

shutup_stupid_compiler = False
for x in seq:
if shutup_stupid_compiler: break
spam
else:
eggs


Thus entering an arms race where the compiler is seen as something to be
silenced rather than something that helps you.

I said that I've written for...else with no break. Why would I do such a
thing? Because I wanted to clearly mark that the code in the else was a
unit of code that went with the for-loop.

Code displays varying levels of cohesiveness. Python lets you group related
code in four levels:

- the function/method;
- the class;
- the module;
- the package


but sometimes you have code which is smaller than a function that needs to
be considered as a unit, but is not enough to justify putting it into a
function. When that happens, we usually delimit it with comments, or
sometimes even just a blank line:

code
that
goes
together

different
bunch
of
code
that
goes
together


So, when I had a bunch of code that included a for-loop, and something
immediately after the for-loop, I could have written:


for x in seq:
block
code that goes
with the loop

different bunch
of code


but I thought it communicated the grouping better to write it as:

for x in seq:
block
else:  # runs after the for
code that goes
with the loop
different bunch

Re: Image loading problem

2016-05-21 Thread huey . y . jiang
Thanks so much! All of methods works!
-- 
https://mail.python.org/mailman/listinfo/python-list