Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Christian Gollwitzer

Am 17.08.16 um 08:39 schrieb Steven D'Aprano:

Quote:

The Python syntax for conditional expressions (introduced in Python 2.5) is

trueval if cond else falseval

I think this is bloody awful. Why couldn’t they have adopted the standard C
syntax, as used in a whole bunch of other C-derivative languages?

cond ? trueval : falseval



Because the C syntax is horrifically ugly,


De gustibus non est disputandum.


whereas the Python syntax is very
close to real English syntax.

"What will you do tonight?"

"Go to the movies, if I finish work on time, otherwise just go home."


This is a non-sequitur. You could as well say, in English:

"If I finish work on time, I go to the movies, otherwise just go home."

In fact, that's how an if-clause looks like in Python

if work_done():
go_to_movies()
else:
go_home()

Do you also struggle reading this?


Every time you read the C syntax, you lose another three minutes off your
lifespan. That's how ugly it is.


It's an acquired taste. I'm not arguing that one is better than the 
other - it depends on what you are used to. I can read both without 
problems, but I avoid writing conditional expressions - if the 
subexpressions are not very simple.


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


Re: pystl

2016-08-17 Thread Poul Riis
I tried the following:

from pystl import PySTL
with PySTL('stl_test.stl') as stl:
stl.add_triangle((0,0,0),(1,0,0),(0,1,0))

I got the following error message:

Traceback (most recent call last):
  File 
"C:/Users/pr/AppData/Local/Programs/Python/Python35-32/Lib/idlelib/pystl_module_test_1.py",
 line 3, in 
with PySTL('stl_test.stl') as stl:
  File 
"c:\users\pr\appdata\local\continuum\anaconda3\lib\site-packages\pystl\pystl.py",
 line 62, in __enter__
self.write_stl_header()
  File 
"c:\users\pr\appdata\local\continuum\anaconda3\lib\site-packages\pystl\pystl.py",
 line 75, in write_stl_header
self.f.write(struct.pack("80s", header_str))
struct.error: argument for 's' must be a bytes object



Poul Riis





Den onsdag den 17. august 2016 kl. 08.49.29 UTC+2 skrev Steven D'Aprano:
> On Wednesday 17 August 2016 16:36, Poul Riis wrote:
> 
> > Can someone deliver a minimal, fully working example with the pystl module,
> > https://pypi.python.org/pypi/pystl/
> > 
> > The only example code mentioned is the following:
> > 
> > with PySTL(‘stl_test.stl’) as stl:
> > stl.add_triangle( (0.0, 0.0, 0.5), (0.0, 1.0, 0.0), (1.0, 1.0, 0.5) )
> > 
> > 
> > but no matter what 'import'-statement I try I cannot make it work.
> 
> Don't make us guess. What have you tried, and what happens when you do? Cut 
> and 
> paste the *actual* code you try, and the *actual* results.
> 
> http://mattgemmell.com/what-have-you-tried/
> 
> http://www.sscce.org/
> 
> 
> > I have installed the module and a program containing only the following line
> > 
> > from pystl import PySTL
> > 
> > runs without any error message.
> 
> Great. Then try this:
> 
> from pystl import PySTL
> with PySTL(‘stl_test.stl’) as stl:
> stl.add_triangle( (0.0, 0.0, 0.5), (0.0, 1.0, 0.0), (1.0, 1.0, 0.5) )
> 
> 
> 
> If it doesn't work, what does it do?
> 
> 
> 
> -- 
> Steve

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread BartC

On 17/08/2016 07:39, Steven D'Aprano wrote:

On Wednesday 17 August 2016 06:59, Lawrence D’Oliveiro wrote:


[Quote]

trueval if cond else falseval



"Go to the movies, if I finish work on time, otherwise just go home."


Is there /any/ programming language that uses a similar form?

Apart from Python, except that it only uses it for expressions, while 
the English uses statements.



Every time you read the C syntax, you lose another three minutes off your
lifespan. That's how ugly it is.



Rather than ask why Python uses `trueval if cond else falseval`, you should ask
why C uses `cond ? trueval : falseval`. Is that documented anywhere?


I'm not fond of C's a ? b : c but the principle is sound. I generally 
use it as:


   (a | b | c)   # /with/ the parentheses

which is a direct equivalent of:

  if a then b else c fi  # from algol 68

So it matches if-statements. And follows the same pattern as:

   (n | a, b, c ... | z)

That is, you are given an index, or condition, and based on that you can 
skip to the option you want and ignore the rest. You don't start with 
the alternative that you may then have to discard.


Anyway a?b:c was existing practice. At least the order of a,b,c could 
have been retained if not the exact syntax.


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


Re: pystl

2016-08-17 Thread Steven D'Aprano
On Wednesday 17 August 2016 18:56, Poul Riis wrote:

> I tried the following:
> 
> from pystl import PySTL
> with PySTL('stl_test.stl') as stl:
> stl.add_triangle((0,0,0),(1,0,0),(0,1,0))
> 
> I got the following error message:


Ah, bad news I am afraid. That looks like a bug in pystl.

I don't think there is anything you can do about it except:

- make sure you have the most recent version of pystl;
- make sure that it supports the version of Python you are using;
- if so, report it as a bug to the pystl project.

> 
> Traceback (most recent call last):
>   File
>   
"C:/Users/pr/AppData/Local/Programs/Python/Python35-32/Lib/idlelib/pystl_module_test_1.py",
>   line 3, in 
> with PySTL('stl_test.stl') as stl:
>   File
>   "c:\users\pr\appdata\local\continuum\anaconda3\lib\site-
packages\pystl\pystl.py",
>   line 62, in __enter__
> self.write_stl_header()
>   File
>   "c:\users\pr\appdata\local\continuum\anaconda3\lib\site-
packages\pystl\pystl.py",
>   line 75, in write_stl_header
> self.f.write(struct.pack("80s", header_str))
> struct.error: argument for 's' must be a bytes object



-- 
Steve

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Jussi Piitulainen
BartC writes:

> On 17/08/2016 07:39, Steven D'Aprano wrote:
>> Rather than ask why Python uses `trueval if cond else falseval`, you
>> should ask why C uses `cond ? trueval : falseval`. Is that documented
>> anywhere?
>
> I'm not fond of C's a ? b : c but the principle is sound. I generally

[- -]

> Anyway a?b:c was existing practice. At least the order of a,b,c could
> have been retained if not the exact syntax.

The original was (c1 -> e1, c2 -> e2, ..., cn -> en) in John McCarthy's
1960 paper on symbolic expressions, with an actual arrow glyph in place
of hyphen-greater-than.

http://www-formal.stanford.edu/jmc/recursive/node2.html (the paper
famously titled "Part I" without any Part II, unless I mistake much.)

It got implemented as (cond (c1 e1) (c2 e2) ... (cn en)), and I'm not
sure when (if c e1 e2) became available as an alternative conditional
expression in the Lisp family (called LISP back then, just like Python
was called PYTHON if it was called at all).

I think Algol 60 had something like "if c then e1 else e2" as an
expression, also due to McCarthy. Keywords probably bold-faced.

I'm perfectly happy with Python's conditional expression syntax, which
cascades surprisingly well. I'm unhappy with C's, not sure why. I think
I would like McCarthy's original syntax.

(Dijkstra had a similar syntax but the clauses were not ordered. Each
guard had to stand alone and any one branch with a true guard could be
chosen. But that may have been a statement only.)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Sivan Greenberg
My first attempt at a large code base was with an Ubuntu project, the
reason I learned Python was Ubuntu's sabdfl insisting on it be used
throughout the OS (back in 2004 I was an Ubuntu developer contributing
packages to main) .

It was easy to get a job , but I started very early when there were not too
much avail devs in my area at the time ;)

Getting to know the language can take an afternoon or a short month.
Mastering can take years, and with the rapid advancements with 3.5 and the
future, you can't know it all. On the other hand, one can masters his own
field of Python e.g. Data science, network programming, web, micro
services.

What's nice about python though that it's easy to ask for help and there's
a wonderful community to help you become a 'master'. My ubuntu project made
me create a co-routine engine in few days without ever knowing about it
before with the help of people at #python on freenode.

It's easy to implement complex things in Python.

-Sivan

On Mon, Aug 15, 2016 at 5:00 PM, Sickfit92  wrote:

> 1. How long did it take you guys to master the language or, let me put it
> this way to completely get the hang and start writing code?
>
> 2. What made you want to learn python?
>
> 3. Was it difficult to learn the language?
>
> 4. Have you been able to get a job out of your new skill?
>
> Thank you guys! I'm pretty much Obsessed with python!
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Sivan Greenberg
Co founder & CTO
Vitakka Consulting
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pystl

2016-08-17 Thread Peter Otten
Poul Riis wrote:

> I tried the following:
> 
> from pystl import PySTL
> with PySTL('stl_test.stl') as stl:
> stl.add_triangle((0,0,0),(1,0,0),(0,1,0))
> 
> I got the following error message:
> 
> Traceback (most recent call last):
>   File
>   
"C:/Users/pr/AppData/Local/Programs/Python/Python35-32/Lib/idlelib/pystl_module_test_1.py",
>   line 3, in 
> with PySTL('stl_test.stl') as stl:
>   File
>   "c:\users\pr\appdata\local\continuum\anaconda3\lib\site-
packages\pystl\pystl.py",
>   line 62, in __enter__
> self.write_stl_header()
>   File
>   "c:\users\pr\appdata\local\continuum\anaconda3\lib\site-
packages\pystl\pystl.py",
>   line 75, in write_stl_header
> self.f.write(struct.pack("80s", header_str))
> struct.error: argument for 's' must be a bytes object

You can fix this particular error by replacing the line

header_str = ''

with 

header_str = b''

in the write_stl_header() function which then becomes:

def write_stl_header(self):
if self.is_bin:
header_str = b''
self.f.write(struct.pack("80s", header_str))
self.write_num_triangles_bin()
else:
self.f.write('solid ' + self.model_name + '\n' )

As this kind of error indicates that the module is primarily used/tested in 
Python 2 there may be other similar problems.

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread D'Arcy J.M. Cain
On Wed, 17 Aug 2016 16:39:30 +1000
Steven D'Aprano  wrote:
> cond ? trueval : falseval 
> 
> Because the C syntax is horrifically ugly, whereas the Python syntax
> is very close to real English syntax.

Or, put another way, Python prefers English over line noise.

-- 
D'Arcy J.M. Cain
System Administrator, Vex.Net
http://www.Vex.Net/ IM:[email protected]
VoIP: sip:[email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Marko Rauhamaa
"D'Arcy J.M. Cain" :

> On Wed, 17 Aug 2016 16:39:30 +1000
> Steven D'Aprano  wrote:
>> cond ? trueval : falseval 
>> 
>> Because the C syntax is horrifically ugly, whereas the Python syntax
>> is very close to real English syntax.
>
> Or, put another way, Python prefers English over line noise.

It can also be confusing. I recently introduced programming to someone
using Python. Because of its similarity with English, they thought
Python understood stuff like:

if x or y == 0:
...

for:

if x == 0 or y == 0:
...


or:

if (x, y) is self.on_point():
...

for:

if self.on_point(x, y):
...


Somewhat analogously, I remember how confusing it was to learn formal
logic in college. I was having a hard time getting the point of
definitions like:

   (x ∧ y) is true iff x is true and y is true

That's because I had learned in highschool that "x ∧ y" was just an
abbreviation of "x and y".


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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Grant Edwards
On 2016-08-17, Marko Rauhamaa  wrote:

> Somewhat analogously, I remember how confusing it was to learn formal
> logic in college. I was having a hard time getting the point of
> definitions like:
>
>(x ∧ y) is true iff x is true and y is true
>
> That's because I had learned in highschool that "x ∧ y" was just an
> abbreviation of "x and y".

It is.  The expression "x ∧ y" is the same as "x and y".  And that
expression is true "iff x is true and y is true".  It's just a sligtly
more explicit way of writing the expression...

-- 
Grant Edwards   grant.b.edwardsYow! I joined scientology
  at   at a garage sale!!
  gmail.com

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Marko Rauhamaa
Grant Edwards :

> On 2016-08-17, Marko Rauhamaa  wrote:
>
>> Somewhat analogously, I remember how confusing it was to learn formal
>> logic in college. I was having a hard time getting the point of
>> definitions like:
>>
>>(x ∧ y) is true iff x is true and y is true
>>
>> That's because I had learned in highschool that "x ∧ y" was just an
>> abbreviation of "x and y".
>
> It is. The expression "x ∧ y" is the same as "x and y". And that
> expression is true "iff x is true and y is true". It's just a sligtly
> more explicit way of writing the expression...

Well, not quite.

Notice the word "and" after "iff". That word is on a different plane
than "∧". The word "and" is on the semantic plane while "∧" is part of
the syntax. (Of course, that would be true even if "∧" were written
"and".)

The formal sentence template

   (x ∧ y)

contains the symbols "(", "∧" and ")". However, "x" and "y" are not part
of the formalism; rather, they are semantic placeholders for arbritrary
formal sentences.

The rest of the definition:

   is true iff x is true and y is true

is plain-English semantics.

In particular, the definition is *not* identical with the formal
sentence:

   (x ∧ y) ↔ (x ∧ y)


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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread MRAB

On 2016-08-17 12:24, Jussi Piitulainen wrote:

BartC writes:


On 17/08/2016 07:39, Steven D'Aprano wrote:

Rather than ask why Python uses `trueval if cond else falseval`, you
should ask why C uses `cond ? trueval : falseval`. Is that documented
anywhere?


I'm not fond of C's a ? b : c but the principle is sound. I generally


[- -]


Anyway a?b:c was existing practice. At least the order of a,b,c could
have been retained if not the exact syntax.


The original was (c1 -> e1, c2 -> e2, ..., cn -> en) in John McCarthy's
1960 paper on symbolic expressions, with an actual arrow glyph in place
of hyphen-greater-than.


[snip]

BCPL, the ancestor of  C, had:

a -> b, c

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


JSON confusion

2016-08-17 Thread Steve Simmons
I'm trying to write a small utility to find the closest railway station 
to a given (UK) postcode but the result is in JSON and I'm not familiar 
with it. I've got as far as extracting the JSON object and I can print 
the first level elements ("success" and "result") but I've totally 
confused myself about how to delve into the rest of the data structure. 
Can anyone point me to a 'how-to' for tackling a fairly complex SJON 
object or give me some pointers. ... or maybe point out if I'm taking an 
unnecessarily complex approach. Initially, I'm Looking to extract 
'stationname', 'distance' and one or two of the coordinate pairs. To be 
honest, I'd rather have some hints rather than the whole solution 
otherwise I'll not learn anything :-) SteveS def main():

import urllib
import urllib.request
import urllib.parse
import urllib.response
import json

url ='https://data.gov.uk/data/api/service/transport/naptan_railway_stations/postcode?postcode=CT16+1ez&distance=2' 
req = urllib.request.urlopen(url)


req_json = req.read()
str_json = req_json.decode("utf-8")

p_json = json.loads(str_json)
print(p_json)
print ('==')
print(repr(p_json))
print('SUCCESS: ',repr(p_json['success']))
print ('==')
print('RESULT : ',repr(p_json['result']))

if __name__ =="__main__":
main()

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


Re: JSON confusion

2016-08-17 Thread Jon Ribbens
On 2016-08-17, Steve Simmons  wrote:
> I'm trying to write a small utility to find the closest railway station 
> to a given (UK) postcode but the result is in JSON and I'm not familiar 
> with it. I've got as far as extracting the JSON object and I can print 
> the first level elements ("success" and "result") but I've totally 
> confused myself about how to delve into the rest of the data structure. 
> Can anyone point me to a 'how-to' for tackling a fairly complex SJON 
> object or give me some pointers. ... or maybe point out if I'm taking an 
> unnecessarily complex approach. Initially, I'm Looking to extract 
> 'stationname', 'distance' and one or two of the coordinate pairs. To be 
> honest, I'd rather have some hints rather than the whole solution 
> otherwise I'll not learn anything :-) SteveS

It's not clear what the problem is. Does this help:

  print(p_json["result"][0]["stationname"])
  print(p_json["result"][0]["latlong"]["coordinates"])

?

(To extract an item from a JSON object you index it with a string,
e.g. ["foo"]; to extract an item from an array you use an integer,
e.g. [0].)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: JSON confusion

2016-08-17 Thread Steve Simmons



On 17/08/2016 17:49, Jon Ribbens wrote:

On 2016-08-17, Steve Simmons  wrote:

I'm trying to write a small utility to find the closest railway station
to a given (UK) postcode but the result is in JSON and I'm not familiar
with it. I've got as far as extracting the JSON object and I can print
the first level elements ("success" and "result") but I've totally
confused myself about how to delve into the rest of the data structure.
Can anyone point me to a 'how-to' for tackling a fairly complex SJON
object or give me some pointers. ... or maybe point out if I'm taking an
unnecessarily complex approach. Initially, I'm Looking to extract
'stationname', 'distance' and one or two of the coordinate pairs. To be
honest, I'd rather have some hints rather than the whole solution
otherwise I'll not learn anything :-) SteveS

It's not clear what the problem is.
Yes, that was the problem!  I wasn't sure if I was being stupid (yes!) 
about the Python or the JSON.  Turns out, it was a bit of both ;-)

Does this help:

   print(p_json["result"][0]["stationname"])
   print(p_json["result"][0]["latlong"]["coordinates"])

?

Yes, immensely.


(To extract an item from a JSON object you index it with a string,
e.g. ["foo"]; to extract an item from an array you use an integer,
e.g. [0].)

Thanks very much, hopefully that'll set me on my way.

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Jussi Piitulainen
MRAB writes:

> On 2016-08-17 12:24, Jussi Piitulainen wrote:
>> BartC writes:
>>
>>> On 17/08/2016 07:39, Steven D'Aprano wrote:
 Rather than ask why Python uses `trueval if cond else falseval`, you
 should ask why C uses `cond ? trueval : falseval`. Is that documented
 anywhere?
>>>
>>> I'm not fond of C's a ? b : c but the principle is sound. I generally
>>
>> [- -]
>>
>>> Anyway a?b:c was existing practice. At least the order of a,b,c could
>>> have been retained if not the exact syntax.
>>
>> The original was (c1 -> e1, c2 -> e2, ..., cn -> en) in John
>> McCarthy's 1960 paper on symbolic expressions, with an actual arrow
>> glyph in place of hyphen-greater-than.
>>
> [snip]
>
> BCPL, the ancestor of  C, had:
>
> a -> b, c

Nice. Add a redundant pair of parentheses and it's the same. (When used
as an expression, a final else-branch is mandatory-ish.)

But C uses -> for something else, I think. And other languages use it
for lambda expressions (succesfully, I think, but then they don't have
it available for this purpose).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What's the best way to minimize the need of run time checks?

2016-08-17 Thread Michael Selik
On Sun, Aug 14, 2016 at 11:01 AM  wrote:

> On Sunday, August 14, 2016 at 7:09:47 AM UTC+1, Paul Rubin wrote:
> > Steven D'Aprano writes:
> > > If the Python community rallies around this "record" functionality and
> > > takes to it like they took too namedtuple
> >
> > I like namedtuple and I think that it's a feature that they're modified
> > by making a new copy.  I know that has overhead but it's palpably
> > bug-avoidant.  I've used them extensively in some programs and they took
> > a considerable burden off my mind compared to using something like
> > structs or records.
>
> You might find this https://glyph.twistedmatrix.com/2016/08/attrs.html an
> interesting read.
>

I disagree with a few points from that blog post.

1. I don't mind typing so much. I like to be explicit. The attrs library
uses some overly-concise abbreviations. For example, what's the meaning of
``@attrs.s`` or ``attrs.ib``?
2. When inheriting from a namedtuple, I use the same class name for the
base and the child, so my reprs look good.
3. I don't bother to fieldnames.split() when passing fieldnames as a
space-separated string, because the split is unnecessary.
4. I *like* that namedtuple is backwards-compatible with tuples, so that
refactoring from tuples to namedtuples is easy.
5. Inheritance is useful. Sure, there are times it fails, but that's true
for any technique.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread MRAB

On 2016-08-17 18:19, Jussi Piitulainen wrote:

MRAB writes:


On 2016-08-17 12:24, Jussi Piitulainen wrote:

BartC writes:


On 17/08/2016 07:39, Steven D'Aprano wrote:

Rather than ask why Python uses `trueval if cond else falseval`, you
should ask why C uses `cond ? trueval : falseval`. Is that documented
anywhere?


I'm not fond of C's a ? b : c but the principle is sound. I generally


[- -]


Anyway a?b:c was existing practice. At least the order of a,b,c could
have been retained if not the exact syntax.


The original was (c1 -> e1, c2 -> e2, ..., cn -> en) in John
McCarthy's 1960 paper on symbolic expressions, with an actual arrow
glyph in place of hyphen-greater-than.


[snip]

BCPL, the ancestor of  C, had:

a -> b, c


Nice. Add a redundant pair of parentheses and it's the same. (When used
as an expression, a final else-branch is mandatory-ish.)

But C uses -> for something else, I think. And other languages use it
for lambda expressions (succesfully, I think, but then they don't have
it available for this purpose).


C uses "->" for dereferencing a pointer to the member of a struct.

If "p" points to a struct (record), then "*p" is that struct, and if 
that struct has a member (field) "m", then that member can be accessed 
by "(*p)->m" (the parens are necessary because of the operator 
precedence). This can be abbreviated to "p->m".


Pascal, on the other hand, dereferences with a postfixed "^", so that 
would be "p^.m".


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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Marko Rauhamaa
MRAB :

> C uses "->" for dereferencing a pointer to the member of a struct.

What "->" is for C, "." is Python and Java.

Python doesn't have C's ".".


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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Grant Edwards
On 2016-08-17, MRAB  wrote:

> C uses "->" for dereferencing a pointer to the member of a struct.
>
> If "p" points to a struct (record), then "*p" is that struct, and if 
> that struct has a member (field) "m", then that member can be accessed 
> by "(*p)->m" (the parens are necessary because of the operator 
> precedence).

ITYM (*p).m

> This can be abbreviated to "p->m".
>
> Pascal, on the other hand, dereferences with a postfixed "^", so that 
> would be "p^.m".

-- 
Grant Edwards   grant.b.edwardsYow! Is this an out-take
  at   from the "BRADY BUNCH"?
  gmail.com

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Terry Reedy

On 8/17/2016 2:39 AM, Steven D'Aprano wrote:

On Wednesday 17 August 2016 06:59, Lawrence D’Oliveiro wrote:



Here

are some examples of that varying mileage.


Quote:

The Python syntax for conditional expressions (introduced in Python 2.5) is

trueval if cond else falseval

I think this is bloody awful.


When this was initially considered, this was the majority view.


Why couldn’t they have adopted the standard C
syntax, as used in a whole bunch of other C-derivative languages?
cond ? trueval : falseval


That particular syntax was not really considered.  At least 10 versions 
using 'if', 'then', 'else', and other tokens were.


They all had the problem of requiring a new keyword such as 'then' or 
some other innovation.



Because the C syntax is horrifically ugly, whereas the Python syntax is very
close to real English syntax.

"What will you do tonight?"

"Go to the movies, if I finish work on time, otherwise just go home."


"If I finish work on on time, go to the movies, otherwise just go home."
is also real English syntax, and to me, more graceful.  It is certainly 
more neutral among the alternatives.  The inverted version implies a 
clear preference for the first alternative.


It would be an interesting exercise to see which order for ternary 
expressions is more common in some large corpus of English text.



Every time you read the C syntax, you lose another three minutes off your
lifespan. That's how ugly it is.


Every time I write or read the Python syntax chosen, I lose time 
rearranging the terms.



The background to the Python ternary operator is documented here:

https://www.python.org/dev/peps/pep-0308/


What the *current* version removed from an earlier version is that there 
was a clear community consensus against the condition-in-the-middle 
syntax Guido proposed and for some version of "if condition then 
True-alternative else False-alternative".  Where consensus was lacking 
was which of multiple 'normal order' alternatives to choose.  Part of 
the problem was a lack of knowledge of which alternative Guido might 
accept.  In any case, a runoff vote among the top contenders was not 
allowed.



Rather than ask why Python uses `trueval if cond else falseval`, you should ask
why C uses `cond ? trueval : falseval`. Is that documented anywhere?


The ordering of the if-then-else terms is obvious.  '?' ending a 
question (in English) is obvious.  ';' was already used to end 
statememts and could not be used here. Could ',' have been used instead 
of ':'?  I am not sure, but it is used elsewhere in C.  ':' is the only 
other within-Englich-sentence separator available.


The ':' naturally translates to 'else', which was already a keyword. 
There was consensus on this.


The problem for a pythonic (wordy) version of the C expression is that 
the word marker for questions, 'if', normally begins rather than ending 
a question*.  So "cond if trueval else falseval" is likely to be 
misinterpreted.  Hence proposals for "cond then trueval else falseval" 
and "if cond then trueval else falseval" and other variations.


* In a construction like "The cock crows?  If so, I must go, else I 
would tarry with thee longer."  the 'if' follows the question, yet 
cannot standalone but must be followed by something referring back to 
the question.


--
Terry Jan Reedy


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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Random832
On Wed, Aug 17, 2016, at 14:27, Terry Reedy wrote:
> That particular syntax was not really considered.  At least 10 versions 
> using 'if', 'then', 'else', and other tokens were.
> 
> They all had the problem of requiring a new keyword such as 'then' or 
> some other innovation.

Why not just if(cond, trueval, falseval), a la Visual Basic?

It's too late to change now, but I'm curious as to whether it was
considered or not.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Marko Rauhamaa
Terry Reedy :

> On 8/17/2016 2:39 AM, Steven D'Aprano wrote:
> "If I finish work on on time, go to the movies, otherwise just go home."
> is also real English syntax, and to me, more graceful.  It is certainly
> more neutral among the alternatives.  The inverted version implies a
> clear preference for the first alternative.
>
> It would be an interesting exercise to see which order for ternary
> expressions is more common in some large corpus of English text.

Python's ternary expression has a distinct Perl flavor to it. However,
the problem with the "then" keyword was valid. Also, Python's
comprehensions already had a postfix "if".

Personally, I'd normally steer clear of ternary conditionals both in C
and Python.

This reminds me of a discussion I had yesterday about why Scheme can't
implement a proper try/finally construct. That's because Scheme supports
continuations; nothing is really final. Python would gain a similar
power if there were a way to cancel exceptions:

 try:
 do_something()
 except ValueError:
 retry 123

where:

 def do_something():
 def_value = raise ValueError
 a += def_value


What Python would then need is a try/nevermind:

 resource = grab_it()
 while True:
  try:
   resource.operate()
  finally:
   resource.release()
   break
  nevermind:
   resource.take_back()


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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread MRAB

On 2016-08-17 18:58, Marko Rauhamaa wrote:

MRAB :


C uses "->" for dereferencing a pointer to the member of a struct.


What "->" is for C, "." is Python and Java.

Python doesn't have C's ".".

C has both stacked-allocated and heap-allocated records. That's not the 
case with Python or Java.


Delphi, which is basically an extended Pascal, allows you to omit the 
"^" when dereferencing a pointer to a field in a record, so you can 
write "p.m" instead of "p^.m" when "p" is a pointer to a record.


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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread MRAB

On 2016-08-17 19:00, Grant Edwards wrote:

On 2016-08-17, MRAB  wrote:


C uses "->" for dereferencing a pointer to the member of a struct.

If "p" points to a struct (record), then "*p" is that struct, and if
that struct has a member (field) "m", then that member can be accessed
by "(*p)->m" (the parens are necessary because of the operator
precedence).


ITYM (*p).m


Correct.


This can be abbreviated to "p->m".

Pascal, on the other hand, dereferences with a postfixed "^", so that
would be "p^.m".




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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread MRAB

On 2016-08-17 19:39, Random832 wrote:

On Wed, Aug 17, 2016, at 14:27, Terry Reedy wrote:

That particular syntax was not really considered.  At least 10 versions
using 'if', 'then', 'else', and other tokens were.

They all had the problem of requiring a new keyword such as 'then' or
some other innovation.


Why not just if(cond, trueval, falseval), a la Visual Basic?

It's too late to change now, but I'm curious as to whether it was
considered or not.


Well, it looks too much like a function call, which don't short-circuit.

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Marko Rauhamaa
MRAB :

> On 2016-08-17 19:39, Random832 wrote:
>> Why not just if(cond, trueval, falseval), a la Visual Basic?
>
> Well, it looks too much like a function call, which don't
> short-circuit.

Well, in Scheme, everything looks like a function call:

(define (deflate x)
  (if (> 0 x)
  (1+ x)
  (1- x)))


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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Terry Reedy

On 8/17/2016 2:07 AM, Steven D'Aprano wrote:


I realise that there are occasions where we might deliberate choose to assign
an intermediate value to its own variable, but all else being equal, which
would you prefer?

#A
alist = []
alist.append(2)
alist.append(4)
alist.append(8)
process(alist)

#B
process([2, 4, 8])

#A
value = 0
for i in range(100):
value += 1
process(value)

#B
process(100)

#A
tmp = get_some_string()
s = tmp[1]
s += tmp[2]
s += tmp[3]
process(s)

#B
process(get_some_string()[1:4])


Up to here, #A is a useless and stupid.  Have you seen such code written?


#A
def callback(btn):
return btn.do_the_thing(42) or default
the_button.setcommand(callback)
process(the_button)

#B
the_button.setcommand(lambda btn: btn.do_the_thing(42) or default)
process(the_button)


This example is *not* parallel to the other 3.  Here, A is useful real 
code and might be preferred for multiple reasons.



If you find yourself preferring B, B, B, A, you might ask yourself what makes a
function different that you prefer to keep temporary functions around where
they're not needed.


When 'callback' is set as the command of the button, it is not 
temporary, but must remain as long as the button remains.  Only the name 
binding is (possibly) disposable.


One may want the function to have a meaningful name that says what it does.

One may want the function to have a name for tracebacks.

In a framework that passes the button to button callbacks (not tk, 
unfortunately), the same callback might be used for multiple buttons. 
(In tk, one must create a wrapper of callback for each button.)


The example is misleading in that the return value of a Button callback 
is likely irrelevant.  (This is true of all tkinter/tk callbacks that I 
can think of.)  More realistic is


#A
def callback(btn):
btn.do_the_thing(42)
the_button.setcommand(callback)

#A'
def cb(btn): btn.do_the_thing(42)
the_button.setcommand(cb)

#B
the_button.setcommand(lambda btn: btn.do_the_thing(42)

I have written code like #B, but #A is more correct, to me, in returning 
None instead of the ignored value of the call.


Beginners often do not understand that the body of a lambda expression 
is evaluated in a new local namespace, and only when the resulting 
function is called, the same as with a def statement.  They then neglect 
to capture current values when writing lambda expressions in a for loop.


In many cases, there is a third alternative using functools.partial.

Production gui code is typically written with classes.  This adds the 
possibility of using bound methods.


This example require the_button to be defined elsewhere.  Typically, the 
command can and should be set when the button is defined, along with 
other options.  Having 'cb' pre-defined may make the defining call more 
readable and the arg list fall on one line rather than two.



Here is a real example from idlelib/help.py

def toc_menu(self, text):
"Create table of contents as drop-down menu."
toc = Menubutton(self, text='TOC')
drop = Menu(toc, tearoff=False)
for lbl, dex in text.parser.toc:
drop.add_command(label=lbl, command=lambda 
dex=dex:text.yview(dex))

toc['menu'] = drop
return toc

The local names 'lbl' and 'dex' were chosen short so that the long line 
would be exactly at the limit of 79 chars.  Here is a rewrite of the for 
loop.


for section_name, line_number in text.parser.toc:
def goto(line=line_number):
text.yview(line)
drop.add_command(label=section_name, command=goto)

To me, this is much better and I intend to commit it.  Thank you for 
prodding me to think through how bad the lambda form can be and to 
rewrite the loop so I don't cringe reading it.


--
Terry Jan Reedy


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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Ben Bacarisse
MRAB  writes:

> On 2016-08-17 18:19, Jussi Piitulainen wrote:
>> MRAB writes:
>>
>>> On 2016-08-17 12:24, Jussi Piitulainen wrote:
 BartC writes:

> On 17/08/2016 07:39, Steven D'Aprano wrote:
>> Rather than ask why Python uses `trueval if cond else falseval`, you
>> should ask why C uses `cond ? trueval : falseval`. Is that documented
>> anywhere?
>
> I'm not fond of C's a ? b : c but the principle is sound. I generally

 [- -]

> Anyway a?b:c was existing practice. At least the order of a,b,c could
> have been retained if not the exact syntax.

 The original was (c1 -> e1, c2 -> e2, ..., cn -> en) in John
 McCarthy's 1960 paper on symbolic expressions, with an actual arrow
 glyph in place of hyphen-greater-than.

>>> [snip]
>>>
>>> BCPL, the ancestor of  C, had:
>>>
>>> a -> b, c
>>
>> Nice. Add a redundant pair of parentheses and it's the same. (When used
>> as an expression, a final else-branch is mandatory-ish.)
>>
>> But C uses -> for something else, I think. And other languages use it
>> for lambda expressions (succesfully, I think, but then they don't have
>> it available for this purpose).
>>
> C uses "->" for dereferencing a pointer to the member of a struct.

Slightly better wording: it uses -> to access a struct member via a
pointer to the struct.

> If "p" points to a struct (record), then "*p" is that struct, and if
> that struct has a member (field) "m", then that member can be accessed
> by "(*p)->m" (the parens are necessary because of the operator
> precedence).

I think you meant (*p).m here because you go on to correct say that ->
offers a shorthand for this rather messy access:

> This can be abbreviated to "p->m".
>
> Pascal, on the other hand, dereferences with a postfixed "^", so that
> would be "p^.m".
>

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Ben Bacarisse
Jussi Piitulainen  writes:

> BartC writes:
>
>> On 17/08/2016 07:39, Steven D'Aprano wrote:
>>> Rather than ask why Python uses `trueval if cond else falseval`, you
>>> should ask why C uses `cond ? trueval : falseval`. Is that documented
>>> anywhere?
>>
>> I'm not fond of C's a ? b : c but the principle is sound. I generally
>
> [- -]
>
>> Anyway a?b:c was existing practice. At least the order of a,b,c could
>> have been retained if not the exact syntax.
>
> The original was (c1 -> e1, c2 -> e2, ..., cn -> en) in John McCarthy's
> 1960 paper on symbolic expressions, with an actual arrow glyph in place
> of hyphen-greater-than.

And BCPL (Martin Richards 1967) took the same arrow and comma syntax.
BCPL spawned B which led to C, but in B Thompson used ? and : but kept
the right-to-left binding.  I think the change was unfortunate because
the arrow works well in various layouts and looks much better when
chained (though that might just be my bias from being a BCPL coder from
way back).


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


Re: JSON confusion

2016-08-17 Thread Terry Reedy

On 8/17/2016 12:35 PM, Steve Simmons wrote:

I'm trying to write a small utility to find the closest railway station
to a given (UK) postcode but the result is in JSON and I'm not familiar
with it. I've got as far as extracting the JSON object and I can print
the first level elements ("success" and "result") but I've totally
confused myself about how to delve into the rest of the data structure.
Can anyone point me to a 'how-to' for tackling a fairly complex SJON
object or give me some pointers. ... or maybe point out if I'm taking an
unnecessarily complex approach. Initially, I'm Looking to extract
'stationname', 'distance' and one or two of the coordinate pairs. To be
honest, I'd rather have some hints rather than the whole solution
otherwise I'll not learn anything :-) SteveS def main():
import urllib
import urllib.request
import urllib.parse
import urllib.response
import json

add   import pprint



url
='https://data.gov.uk/data/api/service/transport/naptan_railway_stations/postcode?postcode=CT16+1ez&distance=2'
req = urllib.request.urlopen(url)

req_json = req.read()
str_json = req_json.decode("utf-8")

p_json = json.loads(str_json)


This result is nexted dicts and lists


print(p_json)
print ('==')
print(repr(p_json))
print('SUCCESS: ',repr(p_json['success']))
print ('==')
print('RESULT : ',repr(p_json['result']))


Replace prints above with
pprint.pprint(p_json)
and you will see the better formatted

{'result': [{'atcocode': '9100DOVERP',
 'crscode': 'DVP',
 'distance': 881.148432224,
 'latlong': {'coordinates': [1.3052936134036113, 
51.12569875059288],

 'crs': {'properties': {'name': 'EPSG4326'},
 'type': 'name'},
 'type': 'Point'},
 'ospoint': {'coordinates': [631380.0, 141464.0],
 'crs': {'properties': {'name': 'EPSG27700'},
 'type': 'name'},
 'type': 'Point'},
 'stationname': 'Dover Priory Rail Station',
 'tiploccode': 'DOVERP'}],
 'success': True}

Use this in combination with Jon Ribbens' answer.


--
Terry Jan Reedy

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Terry Reedy

On 8/17/2016 2:43 PM, Marko Rauhamaa wrote:

Terry Reedy :


On 8/17/2016 2:39 AM, Steven D'Aprano wrote:
"If I finish work on on time, go to the movies, otherwise just go home."
is also real English syntax, and to me, more graceful.  It is certainly
more neutral among the alternatives.  The inverted version implies a
clear preference for the first alternative.

It would be an interesting exercise to see which order for ternary
expressions is more common in some large corpus of English text.


Python's ternary expression has a distinct Perl flavor to it.


One of the ironies (or puzzles) of Guido's choice is that he once 
condemned Perl's 'value if cond' as wretched.  I never got an answer as 
to whether he changed his mind on that or if adding 'else otherval' made 
it unwretched.  Whatever the case, it does not matter to me now. I once 
'boycotted' the ternary but now use it where I think it better than the 
alternative.


--
Terry Jan Reedy

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Terry Reedy

On 8/17/2016 2:39 PM, Random832 wrote:

On Wed, Aug 17, 2016, at 14:27, Terry Reedy wrote:

That particular syntax was not really considered.  At least 10 versions
using 'if', 'then', 'else', and other tokens were.

They all had the problem of requiring a new keyword such as 'then' or
some other innovation.


Why not just if(cond, trueval, falseval), a la Visual Basic?

It's too late to change now, but I'm curious as to whether it was
considered or not.


It is already valid Python, parsed as 'if' 'tuple'

>>> if(1,2): 3

3

A space after 'if' is not optional if the next char is an identifier 
char, as in 'ifx' as this is parsed as the identifier 'ifx', not 'if' 'x'.


Anyone can define an iff(cond, true_func, false_func) function

def iff(cond, f_true, f_false):
return (f_true if cond else f_false)()

or a non-short-circuiting iff(cond, true_val, false_val) function, but 
it hardly seems worth the effort.


--
Terry Jan Reedy

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Lawrence D’Oliveiro
On Thursday, August 18, 2016 at 6:28:06 AM UTC+12, Terry Reedy wrote:
>
>> Why couldn’t they have adopted the standard C
>> syntax, as used in a whole bunch of other C-derivative languages?
>> cond ? trueval : falseval
> 
> That particular syntax was not really considered.  At least 10 versions 
> using 'if', 'then', 'else', and other tokens were.
> 
> They all had the problem of requiring a new keyword such as 'then' or 
> some other innovation.

What was wrong with adopting the C syntax? That would have introduced “?” as a 
new symbol. What impact what that have had on existing Python code? None that I 
can think of.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Lawrence D’Oliveiro
On Thursday, August 18, 2016 at 5:53:14 AM UTC+12, MRAB wrote:

> C uses "->" for dereferencing a pointer to the member of a struct.

The only reason why “s->f” was added was because “(*s).f” was considered an 
unwieldy thing to have to write all the time.

And the only thing that made that unwieldy was that pointer dereferencing was a 
prefix operator, rather than postfix as in Pascal.

> Pascal, on the other hand, dereferences with a postfixed "^", so that 
> would be "p^.m".

And you will notice that nobody felt the need for an alternative form to 
abbreviate that.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Lawrence D’Oliveiro
On Thursday, August 18, 2016 at 6:28:06 AM UTC+12, Terry Reedy wrote:
>> https://www.python.org/dev/peps/pep-0308/
> 
> What the *current* version removed from an earlier version is that there 
> was a clear community consensus against the condition-in-the-middle 
> syntax Guido proposed and for some version of "if condition then 
> True-alternative else False-alternative".  Where consensus was lacking 
> was which of multiple 'normal order' alternatives to choose.  Part of 
> the problem was a lack of knowledge of which alternative Guido might 
> accept.  In any case, a runoff vote among the top contenders was not 
> allowed.

Sounds like Conway’s Law strikes again: a flawed development process led to the 
creation of a flawed solution.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Lawrence D’Oliveiro
On Thursday, August 18, 2016 at 8:25:37 AM UTC+12, Terry Reedy wrote:
>
>  for section_name, line_number in text.parser.toc:
>  def goto(line=line_number):
>  text.yview(line)
>  drop.add_command(label=section_name, command=goto)

You don’t think of that as having its own bit of subtle nastiness?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Chris Angelico
On Thu, Aug 18, 2016 at 9:13 AM, Dennis Lee Bieber
 wrote:
> On Wed, 17 Aug 2016 18:52:22 +0100, MRAB 
> declaimed the following:
>
>
>>
>>If "p" points to a struct (record), then "*p" is that struct, and if
>>that struct has a member (field) "m", then that member can be accessed
>>by "(*p)->m" (the parens are necessary because of the operator
>>precedence). This can be abbreviated to "p->m".
>>
>
> I'd have to test, but I think
>
> (*p).m  is what is equivalent top->m
>
> IE; dereference the pointer, and then access the member of the struct

Folks, read the whole thread before posting :) This was a simple error
that has already been mentioned earlier in the thread. (Sorry to
single you out, Dennis - I'm not trying to hate on you personally
here.)

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Terry Reedy

On 8/17/2016 7:13 PM, Lawrence D’Oliveiro wrote:

On Thursday, August 18, 2016 at 8:25:37 AM UTC+12, Terry Reedy wrote:


 for section_name, line_number in text.parser.toc:
 def goto(line=line_number):
 text.yview(line)
 drop.add_command(label=section_name, command=goto)


You don’t think of that as having its own bit of subtle nastiness?


No, you will have to be explicit.


--
Terry Jan Reedy


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


type lookuperror

2016-08-17 Thread meInvent bbird
would like to check errors for every function i run, 
got error type lookuperror

def checkexception(func, **kwargs):
try:
result = func(*tuple(value for _, value in kwargs.iteritems()))
except:
print "Unexpected error:", sys.exc_info()[0]
try: 
print(func.__doc__)
except:
print("no doc error")
   

>>> mm =checkexception("".encode,encoding='ascii',errors='ignore')
Unexpected error: 
S.encode([encoding[,errors]]) -> object

Encodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that is able to handle UnicodeEncodeErrors.


for p in val_list:
   for k, v in p.items():
   if k == "tenant_id":
   print(v)
   m = v
   ten = checkexception(keystone_client.tenants.get, 
checkexception(m.encode,encoding='ascii',errors'ignore'))
   print(ten.name)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: type lookuperror

2016-08-17 Thread Chris Angelico
On Thu, Aug 18, 2016 at 12:13 PM, meInvent bbird  wrote:
> would like to check errors for every function i run,
> got error type lookuperror
>
> def checkexception(func, **kwargs):
> try:
> result = func(*tuple(value for _, value in kwargs.iteritems()))
> except:
> print "Unexpected error:", sys.exc_info()[0]
> try:
> print(func.__doc__)
> except:
> print("no doc error")
>

I'm going to be brutally honest, and simply say that this is terrible
code. I'm not even going to _try_ to fix it. Instead, here's a
completely rewritten form:

def checkexception(func, *args, **kwargs):
try:
result = func(*args, **kwargs)
except BaseException as e:
print("Exception raised: %s" % e)
try: print(func.__doc__)
except AttributeError: pass
raise # Let the exception keep happening.

But really, there are even better ways to do this. Just let the
exception happen, and then use something like ipython to help you
analyze the traceback.

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Larry Hudson via Python-list

On 08/17/2016 04:24 AM, Jussi Piitulainen wrote:
...

http://www-formal.stanford.edu/jmc/recursive/node2.html (the paper
famously titled "Part I" without any Part II, unless I mistake much.)



Totally OT here, but...

This reminds me of a old record I have with the (deliberately tongue-in-cheek) title "Joe 
'Fingers' Karr and Ira Ironstrings Together for the Last Time, Volume I".  Of course, there was 
never a Volume II either.  [In case you don't know those performers:  Joe 'Fingers' Karr was the 
stage-name of Joe Busch when he played honky-tonk style piano, Ira Ironstrings (don't know real 
name) played banjo.]


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


The Joys Of Data-Driven Programming

2016-08-17 Thread Lawrence D’Oliveiro
Problem: let the user specify certain parameters for a screen display (width, 
height, diagonal, pixel density, pixels across, pixels down, optimum viewing 
distance) and from the ones specified, work out the parameters which were not 
specified.

Solution: set up a table of rules  listing 
all the ways in which parameters can be computed from other parameters. (The 
table is called “paramdefs”.)

This one table saves so much code. It is used to drive the command-line parsing:

opts, args = getopt.getopt \
  (
sys.argv[1:],
"",
list(k + "=" for k in paramdefs)
  )

and again:

params = dict((k, None) for k in paramdefs) # None indicates unspecified 
parameter value
for keyword, value in opts :
if keyword.startswith("--") :
param = keyword[2:]
params[param] = paramdefs[param]["parse"](value)
#end if
#end for

and of course the actual parameter dependency determinations and value 
calculations:

while True :
# try to calculate all remaining unspecified parameter values
did_one = False
undone = set()
for param in params :
if params[param] == None :
calculate = paramdefs[param]["calculate"]
trycalc = iter(calculate.keys())
while True :
# try next way to calculate parameter value
trythis = next(trycalc, None)
if trythis == None :
# run out of ways
undone.add(param)
break
#end if
if all(params[k] != None for k in trythis) :
# have all values needed to use this calculation
params[param] = calculate[trythis](*tuple(params[k] for 
k in trythis))
did_one = True
break
#end if
#end while
#end if
#end for
if len(undone) == 0 or not did_one :
break # all done, or can't make further progress
#end while

I also did the same sort of thing in Java for Android 
. Guess which version is more 
concise...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Lawrence D’Oliveiro
On Thursday, August 18, 2016 at 12:55:33 PM UTC+12, Terry Reedy wrote:
>
> On 8/17/2016 7:13 PM, Lawrence D’Oliveiro wrote:
>
>> On Thursday, August 18, 2016 at 8:25:37 AM UTC+12, Terry Reedy wrote:
>>>
>>>  for section_name, line_number in text.parser.toc:
>>>  def goto(line=line_number):
>>>  text.yview(line)
>>>  drop.add_command(label=section_name, command=goto)
>>
>> You don’t think of that as having its own bit of subtle nastiness?
> 
> No, you will have to be explicit.

That’s not my idea of being “explicit” at all. I hit a similar issue here 
. My solution took this sort of form:

...
#end Face

def def_face_props(celf) :
# get/set index, upem and glyph_count all have the same form:
# all these properties are unsigned integers.

def def_face_prop(propname) :
# need separate inner function so each method gets
# correct values for hb_getter and hb_setter
hb_getter = "hb_face_get_%s" % propname
hb_setter = "hb_face_set_%s" % propname

def getter(self) :
return \
getattr(hb, hb_getter)(self._hbobj)
#end getter

def setter(self, newval) :
getattr(hb, hb_setter)(self._hbobj, newval)
#end setter

getter.__name__ = propname
getter.__doc__ = "the %s property." % propname
setter.__name__ = propname
setter.__doc__ = "sets the %s property." % propname
propmethod = property(getter)
propmethod = propmethod.setter(setter)
setattr(celf, propname, propmethod)
#end def_face_prop

#begin def_face_props
for propname in ("index", "upem", "glyph_count") :
def_face_prop(propname)
#end for
#end def_face_props
def_face_props(Face)
del def_face_props
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: type lookuperror

2016-08-17 Thread meInvent bbird
when try keystone_client.tenants.get
got error,

isn't this method for all kinds of function?

>>> m = "4c9a0da00b904422a23341e35be7f8d7"
>>> ten = checkexception(keystone_client.tenants.get, 
>>> tenant_id=checkexception(m.encode,encoding='ascii',errors='ignore'))
Unexpected error: 
None




On Thursday, August 18, 2016 at 10:22:43 AM UTC+8, Chris Angelico wrote:
> On Thu, Aug 18, 2016 at 12:13 PM, meInvent bbird  wrote:
> > would like to check errors for every function i run,
> > got error type lookuperror
> >
> > def checkexception(func, **kwargs):
> > try:
> > result = func(*tuple(value for _, value in kwargs.iteritems()))
> > except:
> > print "Unexpected error:", sys.exc_info()[0]
> > try:
> > print(func.__doc__)
> > except:
> > print("no doc error")
> >
> 
> I'm going to be brutally honest, and simply say that this is terrible
> code. I'm not even going to _try_ to fix it. Instead, here's a
> completely rewritten form:
> 
> def checkexception(func, *args, **kwargs):
> try:
> result = func(*args, **kwargs)
> except BaseException as e:
> print("Exception raised: %s" % e)
> try: print(func.__doc__)
> except AttributeError: pass
> raise # Let the exception keep happening.
> 
> But really, there are even better ways to do this. Just let the
> exception happen, and then use something like ipython to help you
> analyze the traceback.
> 
> ChrisA

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


Why monkey patching on module object doesn't work ?

2016-08-17 Thread Shiyao Ma
Hi,

I am using Python2.

For the following snippet,

http://ideone.com/i36pKO

I'd suppose the dummy_func would be invoked, but seems not.

Indeed, heapq.heapify does invoke cmp_lt per here:
https://hg.python.org/cpython/file/2.7/Lib/heapq.py#l136

So why this way of monkey patching failed?



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


Re: The Joys Of Data-Driven Programming

2016-08-17 Thread Marko Rauhamaa
Lawrence D’Oliveiro :

> Solution: set up a table of rules

Without judging the individual merits of rules for your use case, I just
want to mention that as a rule, I dislike rules. Rule languages tend to
grow out of all bounds, always remain deficient and have impenetrable,
ad-hoc semantics.

Instead of rules, I prefer programming language hooks. I do realize that
with the power comes a large can of worms.

> #end if
> #end for

Consider leaving these out.


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


Re: Why monkey patching on module object doesn't work ?

2016-08-17 Thread Ian Kelly
On Wed, Aug 17, 2016 at 10:14 PM, Shiyao Ma  wrote:
> Hi,
>
> I am using Python2.
>
> For the following snippet,
>
> http://ideone.com/i36pKO
>
> I'd suppose the dummy_func would be invoked, but seems not.
>
> Indeed, heapq.heapify does invoke cmp_lt per here:
> https://hg.python.org/cpython/file/2.7/Lib/heapq.py#l136
>
> So why this way of monkey patching failed?

Because of this:
https://hg.python.org/cpython/file/2.7/Lib/heapq.py#l351

When you call heapq.heapify, it's not actually calling the reference
implementation in that file. It's actually calling a C implementation
that totally ignores everything in that module.

If you really want to do this, you can disable the C implementation by
adding this before importing heapq:

import sys
sys.modules['_heapq'] = None

This marks the _heapq module as not found in the module cache, which
prevents he module loader from trying to import it, resulting in heapq
using the reference implementation instead.

I don't recommend doing this, however. You'd be disabling the more
efficient implementation in order to monkey-patch an undocumented
function that should be considered an implementation detail. For
example, that cmp_lt function doesn't even exist in Python 3:
https://hg.python.org/cpython/file/tip/Lib/heapq.py
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Joys Of Data-Driven Programming

2016-08-17 Thread Chris Angelico
On Thu, Aug 18, 2016 at 2:47 PM, Marko Rauhamaa  wrote:
> Lawrence D’Oliveiro :
>
>> Solution: set up a table of rules
>
> Without judging the individual merits of rules for your use case, I just
> want to mention that as a rule, I dislike rules. Rule languages tend to
> grow out of all bounds, always remain deficient and have impenetrable,
> ad-hoc semantics.

So you'd be with the Queen Elsa in singing "Doğru yanliş, bir kural
yok"? (I figure this song's famous enough that you probably know what
I mean even without seeing it in English.)

Rule-based code adds a level of abstraction above raw code. Thing is,
though, I actually have no idea about the merits of this exact
example, because (a) the actual rules don't seem to be there, and (b)
there's a lot of guff in the code that makes it very hard to skim. (I
include the "#end if" lines as guff. They're nothing but distraction,
plus a good chance at mismatching stuff when you edit.

Here's how *I* would do this kind of problem.
> Problem: let the user specify certain parameters for a screen display (width, 
> height, diagonal, pixel density, pixels across, pixels down, optimum viewing 
> distance) and from the ones specified, work out the parameters which were not 
> specified.
>

For each parameter, define zero or more sets of parameters from which
it can be calculated. Then iterate over the parameters you don't have,
iterate over the sets, and when you find one that's <= the parameters
you have, call the corresponding function. It's a variant of a
rule-based solution, where the rules are functions tagged with a
decorator.

parameters = defaultdict(dict)
def param(func):
target = func.__name__
source = func.__code__.co_varnames[:func.__code__.co_argcount]
parameters[target][frozenset(source)] = func
return func

@param
def width(height, diagonal):
"""Calculate the width from the height and diagonal"""
# Probably the wrong way to calculate this but whatev, this is an example
return diagonal*diagonal - height*height

@param
def width(pixel_density, pixels_across):
return pixels_across / pixel_density

@param
def diagonal(height, width):
return math.hypot(height, width)

# ... etc etc etc

def make_display(**args):
for kwd, sources in parameters.items():
if kwd in args: continue
for source, func in sources.items():
if source <= set(args):
args[kwd] = func(**{arg:args[arg] for arg in source})
break
else:
# TODO: Queue this for retry down below, or something
if set(args) <= set(parameters):
raise InsufficientInformation


This is a variant of data-driven code. The work is broken out into
individual functions whose names and parameters are used to create the
lookups. Then the actual searching is fairly compact (and could be
done better than this, too). You may notice that very little of this
code is actually aware of specific parameter names - only the formula
functions themselves. Everything else is completely generic.

(There may be bugs in the above code. It's completely untested.
Correction: The above code is completely untested, therefore there are
definitely bugs in it.)

ChrisA

PS. "No right, no wrong, no rules for me".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Gregory Ewing

Terry Reedy wrote:
What the *current* version removed from an earlier version is that there 
was a clear community consensus against the condition-in-the-middle 
syntax Guido proposed


The way I remember it, condition-in-the-middle was first
suggested by others, and Guido expressed dislike for it
initially. Then about a year later he suddenly changed his
mind and accepted it.

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Jussi Piitulainen
Ben Bacarisse writes:

> Jussi Piitulainen writes:
>
>> BartC writes:
>>
>>> On 17/08/2016 07:39, Steven D'Aprano wrote:
 Rather than ask why Python uses `trueval if cond else falseval`, you
 should ask why C uses `cond ? trueval : falseval`. Is that documented
 anywhere?
>>>
>>> I'm not fond of C's a ? b : c but the principle is sound. I generally
>>
>> [- -]
>>
>>> Anyway a?b:c was existing practice. At least the order of a,b,c could
>>> have been retained if not the exact syntax.
>>
>> The original was (c1 -> e1, c2 -> e2, ..., cn -> en) in John McCarthy's
>> 1960 paper on symbolic expressions, with an actual arrow glyph in place
>> of hyphen-greater-than.
>
> And BCPL (Martin Richards 1967) took the same arrow and comma syntax.
> BCPL spawned B which led to C, but in B Thompson used ? and : but kept
> the right-to-left binding.  I think the change was unfortunate because
> the arrow works well in various layouts and looks much better when
> chained (though that might just be my bias from being a BCPL coder from
> way back).
>
> 

I share the preference but have never programmed in a language that uses
an arrow syntax.

Much thanks for the history. (To MRAB, too.)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Gregory Ewing

Terry Reedy wrote:
One of the ironies (or puzzles) of Guido's choice is that he once 
condemned Perl's 'value if cond' as wretched.


I don't think that's the same thing. Perl allows
'statement if cond' as an alternative way of writing
"if (cond) statement'. Nobody has ever seriously
considered allowing two ways to write if *statements*
in Python.

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