Re: Procedures and functions [was Re: Why not allow empty code blocks?]

2016-07-30 Thread Chris Angelico
On Sun, Jul 31, 2016 at 4:40 PM, Steven D'Aprano  wrote:
>> While neither is a syntax error, the latter is definitely a run-time
>> error:
>>
> mylist.sort().reverse()
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> AttributeError: 'NoneType' object has no attribute 'reverse'
>
> Hence my description of it as a perplexing source of mystery bugs. How did
> mylist suddenly turn into None?
>
> Well, it didn't, but it sure looks like it did, for those who didn't realise
> that sort() is intended to be used *as if* it were a procedure with no
> return value. If it *actually* had no return value, Python could give a
> more useful error message:
>
> ProcedureError: list.sort() has no return value

Fortunately, a linter can pick this up (maybe even right in your
editor, before you move off the line of code). Particularly if type
hints are available, a linter can say "Hey, this function always
returns None, and you're assigning it to something - that looks
wrong".

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


Re: Procedures and functions [was Re: Why not allow empty code blocks?]

2016-07-30 Thread Rustom Mody
On Sunday, July 31, 2016 at 12:10:33 PM UTC+5:30, Steven D'Aprano wrote:
> On Sun, 31 Jul 2016 02:01 pm, D'Arcy J.M. Cain wrote:
> 
> > On Sun, 31 Jul 2016 13:32:16 +1000
> > Steven D'Aprano wrote:
> >> Many beginners make the mistake of writing:
> >> 
> >> mylist = mylist.sort()
> >> 
> >> or try to write:
> >> 
> >> mylist.sort().reverse()
> >> 
> >> If we had procedures, that would be an obvious error (possibly even a
> >> compile-time syntax error) instead of a perplexing source of mystery
> >> bugs.
> > 
> > While neither is a syntax error, the latter is definitely a run-time
> > error:
> > 
>  mylist.sort().reverse()
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > AttributeError: 'NoneType' object has no attribute 'reverse'
> 
> Hence my description of it as a perplexing source of mystery bugs. How did
> mylist suddenly turn into None?
> 
> Well, it didn't, but it sure looks like it did, for those who didn't realise
> that sort() is intended to be used *as if* it were a procedure with no
> return value. If it *actually* had no return value, Python could give a
> more useful error message:
> 
> ProcedureError: list.sort() has no return value
> 
> as soon as the interpreter tries to push the non-existent return value onto
> the stack. Python can't do that, because None is an ordinary object line
> any other. There's no practical way for Python to distinguish (whether at
> compile-time or run-time) None as an ordinary object from None as a
> stand-in for "no object at all".
> 
> In practice, for moderately experienced programmers, the difference is minor
> and most people quickly learn how to debug "None object has no attribute"
> exceptions. But for a teaching language where we want to be stricter about
> the dichotomy of:
> 
> - subroutines that transform values (functions); and
> - subroutines with side-effects (procedures)
> 
> its a little sub-optimal.

That’s a nice summary of my position — tnx.

Not that python as a production language with a fundamentally dynamic DNA needs
to change. Rather that beginners not having procedure←→function as abstractions
of effect←→value are subjected to a more than necessarily arduous learning curve
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Rustom Mody
On Sunday, July 31, 2016 at 9:43:03 AM UTC+5:30, Chris Angelico wrote:
> On Sun, Jul 31, 2016 at 1:34 PM, Rustom Mody  wrote:
> > to
> >> > teach the actual theory of programming languages (lambda calculus, lists
> >> > as a foundation unit for all other data structures), Scheme was an ideal
> >> > choice for teaching these fundamentals.
> >>
> >> People misuse language. You say that scheme was "ideal". That literally
> >> means that there is *not one single thing* about Scheme that isn't PERFECT
> >> for the task, that it reaches a faultless standard of perfection lacking
> >> all weaknesses.
> >
> > As usual you are making up definitions and being ridiculous.
> > In most common usage ‘ideal’ is used as opposed to ‘real’
> 
> Oh? So you're saying that there are other real choices for teaching,
> but Scheme is merely ideal?
> 
> The phrase "an ideal choice", if taken at face value, means exactly
> what Steven is claiming: that it is logically impossible for there to
> be any better choice, because this is the greatest idea you could
> have. It is the very definition of "better" and "worse", in that a
> better option is nearer to the ideal than a worse one.
> 
> ChrisA

Michael said: [emphasis and re-permuting mine]

> Scheme was an ideal choice FOR TEACHING THE FUNDAMENTALS: [viz.]
> the actual theory of programming languages — lambda calculus, lists
> as a foundation unit for all other data structures.
> [Whereas] Python would have been alright to teach "programming"…

And it started with me saying that MIT has switched from scheme to python
because: [MIT prof’s not my opinion] Not that python is any better at 
fundamentals than scheme but because hacking together a solution is more 
centerstage today than clarity in covering fundamentals.

IOW those guys like Michael are pitting real vs ideal
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Procedures and functions [was Re: Why not allow empty code blocks?]

2016-07-30 Thread Steven D'Aprano
On Sun, 31 Jul 2016 02:01 pm, D'Arcy J.M. Cain wrote:

> On Sun, 31 Jul 2016 13:32:16 +1000
> Steven D'Aprano  wrote:
>> Many beginners make the mistake of writing:
>> 
>> mylist = mylist.sort()
>> 
>> or try to write:
>> 
>> mylist.sort().reverse()
>> 
>> If we had procedures, that would be an obvious error (possibly even a
>> compile-time syntax error) instead of a perplexing source of mystery
>> bugs.
> 
> While neither is a syntax error, the latter is definitely a run-time
> error:
> 
 mylist.sort().reverse()
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'NoneType' object has no attribute 'reverse'

Hence my description of it as a perplexing source of mystery bugs. How did
mylist suddenly turn into None?

Well, it didn't, but it sure looks like it did, for those who didn't realise
that sort() is intended to be used *as if* it were a procedure with no
return value. If it *actually* had no return value, Python could give a
more useful error message:

ProcedureError: list.sort() has no return value

as soon as the interpreter tries to push the non-existent return value onto
the stack. Python can't do that, because None is an ordinary object line
any other. There's no practical way for Python to distinguish (whether at
compile-time or run-time) None as an ordinary object from None as a
stand-in for "no object at all".

In practice, for moderately experienced programmers, the difference is minor
and most people quickly learn how to debug "None object has no attribute"
exceptions. But for a teaching language where we want to be stricter about
the dichotomy of:

- subroutines that transform values (functions); and
- subroutines with side-effects (procedures)

its a little sub-optimal.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Paul Rubin
Steven D'Aprano  writes:
>> Maybe.  Lisp and Scheme are great languages to teach the theory..
> Doesn't sound like a good teaching language to me.>
> Meta-reasoning is harder than regular reasoning. That's why metaclasses are
> harder to use than ordinary classes.

Python metaclasses are monstrously more complicated than simple
metacircular evaluators in Scheme.

> Beginners have trouble enough learning even simple features of
> languages, and you want to drop them straight into meta-languages as
> their first taste of programming?

The classic SICP course didn't deal with meta-evaluation until towards
the end.  It starts out with simple computation, then goes into higher
order functions, lazy evaluation, logic programming, and other topics;
finally it shows how to write a Scheme compiler in Scheme.

The book is really great, highly recommended, full text online:
   https://www.mitpress.mit.edu/sicp/

Wadler critique (note: Miranda is a forerunner of Haskell):

  https://www.cs.kent.ac.uk/people/staff/dat/miranda/wadler87.pdf

> I suspect that Lisp/Scheme would make a really good *third* language. Or
> even fourth.

FORTH heh heh ;-)

> - For starters, there's the whole parentheses thing. 

That stops being a problem almost immediately, really.

> It has always perplexed me that Lisp's prefix notation is held up as
> the /sine qua non/ of elegance and power, while Forth is ignored if not
> ridiculed.

A postfix ("concatenative") language like Factor, with Forth-like syntax
but Scheme-like semantics, would be an interesting alternative to
Scheme.  But traditional Forth, while cool in its own way, is extremely
low level, especially using the classical pure stack-oriented style.
Lots of mucking with raw machine addresses, no type system either at
compile time or runtime, not even local variables in the Forth loved by
purists.  Consider multiplying two complex numbers a+bi and c+di in
Scheme (never mind that it has an actual complex datatype), giving a
2-element list (x y) representing x+yi which is (ac-bd) + i(ad+bc):

  (define (z* a b c d)
 (list (- (* a c) (* b d)) (+ (* a d) (* b c

Yeah there's parentehses etc. but it's obvious how to write it.

Now let's try that in Forth.  It takes some head scratching--this is the
best I can do:

: ad+bc ( a b c d -- x ) -rot * -rot * + ;
: ac-bd ( a b c d -- y ) rot * >r * r> - ;
: z* ( a b c d -- x y ) 2over 2over ad+bc >r ac-bd r> ;

Have a look at the table of contents of SICP even if you don't read the
whole book, and imagine covering those topics in a Forth-based course.

You've probably already seen this too:

   http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html

The ideas in that paper translate naturally into Haskell and with a bit
of exertion into Scheme, but would be painful in Forth.

> Lisp started as an academic language in the computer science
> department,

Actually math department (there was no such thing as CS then) but ok.

> while Forth was merely a practical language invented to control
> telescopes,

Forth was actually inspired by Lisp, and was invented while Chuck Moore
was working at a carpet company (he got into telescope control later).
It's still interesting for hardware control but painful for anything
that doesn't fit easily into fixed-width cells and not much use of
memory allocation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Procedures and functions [was Re: Why not allow empty code blocks?]

2016-07-30 Thread Random832
On Sun, Jul 31, 2016, at 00:01, D'Arcy J.M. Cain wrote:
> On Sun, 31 Jul 2016 13:32:16 +1000
> Steven D'Aprano  wrote:
> > Many beginners make the mistake of writing:
> > 
> > mylist = mylist.sort()
> > 
> > or try to write:
> > 
> > mylist.sort().reverse()
> > 
> > If we had procedures, that would be an obvious error (possibly even a
> > compile-time syntax error) instead of a perplexing source of mystery
> > bugs.
> 
> While neither is a syntax error, the latter is definitely a run-time
> error:

The only way to make it a syntax error would be to have a different
syntax for *calling* procedures. Barring that, all you can do is make
the first one a run-time error.

As Python is a dynamic language, mylist.sort is an object which is
resolved at runtime. When you call this object, its __call__ method is
called and returns the None object. This object is valid for very few
operations (it can be assigned to a variable [or returned], treated as a
boolean, compared for equality, or converted to a string).

In some other languages, procedures have a static return type (often
called "void") which is valid for even fewer operations. You can use it
as a statement expression or within certain contexts (the left side of
C's comma operator, for example) where the value of an expression is
always discarded.

In a hypothetical Python with procedures but no separate syntax for
calling them, you would need to define the __call__ protocol in a way
that it can indicate that the called object is a procedure. Though, it
could probably be handled at the python level by just allowing "return"
or running off the end to do this, requiring "return None" for the
explicit return of a None object.. The real cost is, it would require
that any operation (such as assigning as a variable, checking it as a
boolean, etc) other than discarding it (including returning it, so you'd
need extra bytecode to check rather than merely leaving tail returns on
the stack) check immediately raise an error. This would add extra
processing to nearly all call sites.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sun, Jul 31, 2016 at 1:51 PM, Random832  wrote:
> On Sat, Jul 30, 2016, at 22:17, Chris Angelico wrote:
>> Yeah. The distinction means you have a fundamental API difference
>> between the procedures (which don't return anything) and the functions
>> (whose return values you mightn't care about).
>
> Not really any more than between functions returning different types -
> which python doesn't distinguish in general. That some languages may
> spell it with a different keyword rather than a special type [such as
> C's void] doesn't mean the fundamental API difference is of a different
> kind.

In C, you can treat any function as a procedure by simply ignoring its
return value, as in Python. So all functions, whether they return int
or float or void, are functions - there's no fundamental difference.
What I'm talking about is having two types of callables:

a = function(x, y)
call procedure x, y

REXX has this distinction at the call site (because of other API
considerations regarding loose expressions), but it's not fundamental;
the second form will ignore any return value, ergo a procedure can be
upgraded to a function without breaking anything. Python has no
distinction whatsoever, requiring all functions to return *something*,
even if it's None. Pike has a concept of void functions, but deep in
the internals, they just return zero, so if you mess with the type
checker and get around the compile-time checks, you'll get zero back.
C... I dunno for sure, and it probably depends on the compiler, but I
just tried it on my gcc, and it looks like it basically takes whatever
happened to be sitting in the accumulator. In all cases, anyone who
wasn't expecting a return value will be fine with a version of the
function that returns something.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sun, Jul 31, 2016 at 1:34 PM, Rustom Mody  wrote:
> to
>> > teach the actual theory of programming languages (lambda calculus, lists
>> > as a foundation unit for all other data structures), Scheme was an ideal
>> > choice for teaching these fundamentals.
>>
>> People misuse language. You say that scheme was "ideal". That literally
>> means that there is *not one single thing* about Scheme that isn't PERFECT
>> for the task, that it reaches a faultless standard of perfection lacking
>> all weaknesses.
>
> As usual you are making up definitions and being ridiculous.
> In most common usage ‘ideal’ is used as opposed to ‘real’

Oh? So you're saying that there are other real choices for teaching,
but Scheme is merely ideal?

The phrase "an ideal choice", if taken at face value, means exactly
what Steven is claiming: that it is logically impossible for there to
be any better choice, because this is the greatest idea you could
have. It is the very definition of "better" and "worse", in that a
better option is nearer to the ideal than a worse one.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sun, Jul 31, 2016 at 1:12 PM, Gregory Ewing
 wrote:
> Chris Angelico wrote:
>>
>> I mean, "for i in 3.5" should start half way down the loop body, complete
>> that loop, and
>> then do three complete loops.
>
>
> +1, this is the best idea for a "loop-and-a-half"
> construct I've ever seen.

It was inspired by Duff's Device, which could then be implemented very
easily by simply true-dividing by eight. :)

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


Re: Procedures and functions [was Re: Why not allow empty code blocks?]

2016-07-30 Thread Chris Angelico
On Sun, Jul 31, 2016 at 1:32 PM, Steven D'Aprano  wrote:
>> It means you can't
>> upgrade something from "always returns None" to "returns the number of
>> objects frobbed" without breaking compat.
>
> You shouldn't ever need to. At least that's the theory. In practice its not
> quite cut and dried. Procedures are for things which purely operate by
> side-effect: they're verbs, doing words:

That's all very well in theory, but as you say, it's far from cut and
dried. Taking the example that started all this off, Python 2 had
'print' as a statement (no return value), but the write method of I/O
streams (eg sys.stdout.write) has a definite and important return
value (the amount written).

As another example, the 'gc' module allows you to trigger garbage
collection immediately. (All examples from CPython. I don't know how
other Pythons handle things, but the specifics don't matter anyway.)
That's very definitely a verb - "go and take out the trash, now" - but
it's a function that returns the number of unreachable objects. More
or less the same concept as write(), in that it does some work and
then returns how much work it did.

So while I agree with Python's decision to make list.sort() return
None rather than the mutated list, I think there's not a dichotomy
here but a spectrum, from "procedure-like" to "function-like". At the
one extreme are control flow statements - it doesn't make any sense
whatsoever to ask about the return value of a "while" statement.
(Though you could define it as the value of the condition expression,
but that's something you want _inside_ the while block, not outside.)
Then you have things that Python has as statements, but which
plausibly could have return values, eg "def" and "class" could return
the function/class. Somewhere toward the middle are gc.collect() and
friends, where you mainly call them for their functionality, not their
return values. Leaning toward functional are the
mutators-with-return-values like list.pop() - there are times when you
don't care about the element, you just want to pop and discard. And
then the most functional of functions would be pure functions like
math.sin(), where they have no side effects whatsoever, just a return
value.

Which ones would you define as procedures and which as functions? Or
can you just define _everything_ as a function, and give them valid,
if meaningless, return values? Yeah.

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


Re: Procedures and functions [was Re: Why not allow empty code blocks?]

2016-07-30 Thread D'Arcy J.M. Cain
On Sun, 31 Jul 2016 13:32:16 +1000
Steven D'Aprano  wrote:
> Many beginners make the mistake of writing:
> 
> mylist = mylist.sort()
> 
> or try to write:
> 
> mylist.sort().reverse()
> 
> If we had procedures, that would be an obvious error (possibly even a
> compile-time syntax error) instead of a perplexing source of mystery
> bugs.

While neither is a syntax error, the latter is definitely a run-time
error:

>>> mylist.sort().reverse()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'NoneType' object has no attribute 'reverse'

-- 
D'Arcy J.M. Cain
System Administrator, Vex.Net
http://www.Vex.Net/ IM:da...@vex.net
VoIP: sip:da...@vex.net
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Random832
On Sat, Jul 30, 2016, at 22:17, Chris Angelico wrote:
> Yeah. The distinction means you have a fundamental API difference
> between the procedures (which don't return anything) and the functions
> (whose return values you mightn't care about).

Not really any more than between functions returning different types -
which python doesn't distinguish in general. That some languages may
spell it with a different keyword rather than a special type [such as
C's void] doesn't mean the fundamental API difference is of a different
kind.

> It means you can't
> upgrade something from "always returns None" to "returns the number of
> objects frobbed" without breaking compat. 

Well, that's something you can't do in general in statically typed
languages. (Once upon a time, C had a default return type of int, and
allowed functions returning it to fall off the end or have a "return;"
statement, but not anymore).

This is ultimately just the static typing argument in miniature,
confused by the fact that some languages declare them with a different
syntax from other functions.

> Conversely, if you decide
> that any function can be called "as a procedure" (this is what REXX
> does, for instance), then you've just merged the two types of callable
> and distinguished them only in usage.
> 
> Personally, I don't see any value to the distinction at all.
> 
> ChrisA
> -- 
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Random832
On Sat, Jul 30, 2016, at 22:10, Steven D'Aprano wrote:
> "while True" doesn't merely emulate an infinite loop, it implements an
> infinite loop without needing dedicated syntax, byte-code or
> implementation. 

Er, it's not like it would need dedicated byte code anyway. The bytecode
of an infinite loop is just an unconditional backward jump*, which we
already have. The peephole optimizer already takes care of it (which
_could_ be considered dedicated implementation; even if it's general
enough to also work with "if True", how many of those do you figure
there really are?)

One argument that exists in favor of a dedicated infinite loop (and
dedicated finite repetition loop) syntax, which I don't personally think
applies to Python, is that the condition (and the whole construct for
"for i in range", for finite repetitions) means additional concepts that
have to be introduced at the same time to people being taught
programming for the first time.

*in fact, the bytecode of while already contains an unconditional
backward jump; there's a conditional forward jump at the top - which is
eliminated, I assume by the peephole optimizer, when the loop condition
is a truthy constant.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Rustom Mody
On Sunday, July 31, 2016 at 8:44:13 AM UTC+5:30, Steven D'Aprano wrote:

> It has always perplexed me that Lisp's prefix notation is held up as
> the /sine qua non/ of elegance and power, while Forth is ignored if not
> ridiculed. Forth is just as expressive as Lisp, just as meta, just as
> customizable. You can create your own syntax in Forth. Forth doesn't have
> macros, because it doesn't need them: you have complete control of what is
> compiled and what is interpreted and when.
> 
> I maintain that Forth would be a better meta-language than Lisp. If you're
> going to require students to learn to think using a grammar which isn't OVS
> or SVO (i.e. infix) then it seems to me that postfix with a stack is easier
> to learn than prefix with parentheses.

That may well be
In principle just flip (f x y) to x y f and we get from Lisp to Forth (or 
postscript)
In practice people have taken the pains to work out much of the theory of CS 
in Lisp. Has it been done in Forth??  Maybe… Dunno…

> On Sun, 31 Jul 2016 04:16 am, Michael Torrie wrote:

> > I'll never use Scheme again in my life, but I'm very 
> > glad to have learned it in my Theory of Programming Languages course at
> > uni.  Python would have been alright to teach "programming," but to
> > teach the actual theory of programming languages (lambda calculus, lists
> > as a foundation unit for all other data structures), Scheme was an ideal
> > choice for teaching these fundamentals.
> 
> People misuse language. You say that scheme was "ideal". That literally
> means that there is *not one single thing* about Scheme that isn't PERFECT
> for the task, that it reaches a faultless standard of perfection lacking
> all weaknesses. 

As usual you are making up definitions and being ridiculous.
In most common usage ‘ideal’ is used as opposed to ‘real’

> That's much stronger than saying "Scheme is the best
> language for...", and much stronger than saying "nothing will ever be
> better". It's saying that nothing *could* be better, because perfection has
> been reached.
> 
> (Yes yes, I know you don't actually mean that, not literally. I'm making a
> rhetorical point.)

Good to know. But its not clear what the point is.
Michael said Lisp is ideal FOR TEACHING 

> 
> 
> > The continued confusion that 
> > pops up on the list from new users on how Python variables work wouldn't
> > be an issue if they came from a Scheme background.  The idea of names
> > and binding of names would make perfect sense to them.
> 
> Of course. But that's because they would have suffered the same confusion
> when learning Scheme, and got past it by their second language, Python.

That’s because variables are first class in lisp and neither-fish-nor-foul class
in python
-- 
https://mail.python.org/mailman/listinfo/python-list


Procedures and functions [was Re: Why not allow empty code blocks?]

2016-07-30 Thread Steven D'Aprano
On Sun, 31 Jul 2016 12:17 pm, Chris Angelico wrote:

> Yeah. The distinction means you have a fundamental API difference
> between the procedures (which don't return anything) and the functions
> (whose return values you mightn't care about). 

Correct.

> It means you can't 
> upgrade something from "always returns None" to "returns the number of
> objects frobbed" without breaking compat. 

You shouldn't ever need to. At least that's the theory. In practice its not
quite cut and dried. Procedures are for things which purely operate by
side-effect: they're verbs, doing words:

sleep
print
run
mangle
append
delete

Functions, on the other hand, are transformations. Functions should never
have side-effects, they should take at least one argument and return a new
value.

length of ...
cosine of ...
the date of [this instant]

That's a fairly important conceptual difference, although as I acknowledge
in practice there's more overlap than one might like.



> Conversely, if you decide 
> that any function can be called "as a procedure" (this is what REXX
> does, for instance), then you've just merged the two types of callable
> and distinguished them only in usage.
> 
> Personally, I don't see any value to the distinction at all.

Oh, there's definitely value. I'm just not sure whether the value is worth
the cost of making the distinction.

Many beginners make the mistake of writing:

mylist = mylist.sort()


or try to write:

mylist.sort().reverse()


If we had procedures, that would be an obvious error (possibly even a
compile-time syntax error) instead of a perplexing source of mystery bugs.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Float

2016-07-30 Thread Rustom Mody
On Saturday, July 30, 2016 at 5:21:44 PM UTC+5:30, Chris Angelico wrote:
> On Sat, Jul 30, 2016 at 9:44 PM, Cai Gengyang  wrote:
> > You mentioned that : A floating point number[2] is number that is not an 
> > integer (and not a
> > complex number)
> >
> > Hence ,
> >
> > 10 is not a floating point number because it is an integer
> > 25 is not a floating point number because it is an integer
> > 7 + 3i is not a floating number because it is a complex number
> > 8 + 5i is not a floating number because it is a complex number.
> >
> > Is 3.0 a floating number ? It is a rational number, not an integer right ?

As Steven pointed out the distinction you need to get is floating vs fixed
Scientific notation is a good analogy to understand.

3 looks smaller than 300
Not so much in scientific notation:

>>> "%g" % 3
'3'
>>> "%g" % 3
'3e+20'
>>> 
In effect the position of the decimal point is captured but not the presumably
non-significant digits

Note this is an analogy.  Unfortunately in practice…
> 
> In a computing context, data types are incredibly significant.

…in practice data types and in particular numeric data types in most
mainstream languages is a total mess.
And becoming an effective programmer means learning to live with/around it.

Some indications of the mess:
>>> .1 + .1 == .2
True
>>> .1 + .1 + .1== .3
False

To get a clue why:
>>> .5 . as_integer_ratio()
(1, 2)   # ie ½
>>> .25 . as_integer_ratio()
(1, 4)  # ie ¼
>>> .1 . as_integer_ratio()
(3602879701896397, 36028797018963968) # ie PPPS!!

Another (and in my opinion bigger) violation that most programming languages
including python make over standard math is that fundamental subset relations
are brazenly violated and then duct-taped-over with something called časting’

ie in math we have
ℕ ⊂ ℤ ⊂ ℚ ⊂ ℝ

In programming float, int are all disjoint
That disjointness is bandaided with casts
These should be in principle reversible

>>> x = 10
>>> float(x)
10.0
>>> int(float(x))
10
>>> int(float(x)) == x
True

# So far so good

>>> y = 10
>>> float(y)
1e+69
>>> int(float(y)) == y
False

# WTF?! Lets see why...

>>> int(float(y))
172531436381529235126158374409646521955518210155479040L

tl;dr Donald Knuth, is considered one of the greatest programmers. Its a good 
idea to follow his example.

In writing Tex he went out of his way to implement his own fixed point
system and avoid using the builtin hardware floating point
https://en.wikipedia.org/wiki/TeX#Development

To the extent its feasible it’s advisable to follow the example of Knuth
[No not writing your own system, but avoiding when/if possible]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sun, 31 Jul 2016 04:16 am, Michael Torrie wrote:

> On 07/30/2016 11:53 AM, Steven D'Aprano wrote:
>> On Sun, 31 Jul 2016 02:29 am, Rustom Mody wrote:
>> 
>>> MIT on practical reasons for python over scheme:
>>>
>>
https://www.wisdomandwonder.com/link/2110/why-mit-switched-from-scheme-to-python
>>> Berkeley on fundamental reasons for the opposite choice:
>>> https://people.eecs.berkeley.edu/~bh/proglang.html
>> 
>> Not a very useful discussion. His argument basically boils down to:
>> 
>> "Lisp came up with some good ideas that were copied by other languages.
>> Therefore Lisp is a good teaching language."
> 
> Maybe.  Lisp and Scheme are great languages to teach the theory of
> programming with because they are so easy to use to build DSLs (all
> within the same syntax as Lisp), and it kind of acts like a
> meta-language.

Doesn't sound like a good teaching language to me.

Meta-reasoning is harder than regular reasoning. That's why metaclasses are
harder to use than ordinary classes. Beginners have trouble enough learning
even simple features of languages, and you want to drop them straight into
meta-languages as their first taste of programming?

I suspect that Lisp/Scheme would make a really good *third* language. Or
even fourth.


> I'll never use Scheme again in my life, but I'm very 
> glad to have learned it in my Theory of Programming Languages course at
> uni.  Python would have been alright to teach "programming," but to
> teach the actual theory of programming languages (lambda calculus, lists
> as a foundation unit for all other data structures), Scheme was an ideal
> choice for teaching these fundamentals.

People misuse language. You say that scheme was "ideal". That literally
means that there is *not one single thing* about Scheme that isn't PERFECT
for the task, that it reaches a faultless standard of perfection lacking
all weaknesses. That's much stronger than saying "Scheme is the best
language for...", and much stronger than saying "nothing will ever be
better". It's saying that nothing *could* be better, because perfection has
been reached.

(Yes yes, I know you don't actually mean that, not literally. I'm making a
rhetorical point.)

Let's look at some problems with Scheme:

- For starters, there's the whole parentheses thing. While its true that
people claim[1] that the experienced Schemer or Lisper stops seeing them,
beginners and students are possibly five or ten years away from being
experienced Schemers. In the meantime, all those nested parentheses hurt
legibility and code comprehension.

- And then there's the use of prefix order of terms (Polish notation). For
the beginner, having to learn in prefix notation instead of infix notation
(which comes much more easily to English speakers) is a major problem.

- Writing DSLs is not something that ought to be encouraged, or at least not
required. DSLs impose a maintenance burden: you know have to learn both the
DSL and the metalanguage it is written in. One needs to be wary of going
there without a good reason.


It has always perplexed me that Lisp's prefix notation is held up as
the /sine qua non/ of elegance and power, while Forth is ignored if not
ridiculed. Forth is just as expressive as Lisp, just as meta, just as
customizable. You can create your own syntax in Forth. Forth doesn't have
macros, because it doesn't need them: you have complete control of what is
compiled and what is interpreted and when.

Perhaps it is because Lisp started as an academic language in the computer
science department, invented by people who knew all the right terms from
formal and complex mathematics (the parts they don't teach undergraduates)
while Forth was merely a practical language invented to control telescopes,
by an astronomer. Perhaps it is because the most popular Forth book
("Starting Forth" by Leo Brodie) shamelessly and intentionally
anthropomorphised the Forth interpreter in order to make it more accessible
to non-academics, while Lisp/Scheme are elitist languages used by elite
academics who, for the most part, would probably stop using Lisp/Scheme if
they became popular outside of university again.

I maintain that Forth would be a better meta-language than Lisp. If you're
going to require students to learn to think using a grammar which isn't OVS
or SVO (i.e. infix) then it seems to me that postfix with a stack is easier
to learn than prefix with parentheses.


> The continued confusion that 
> pops up on the list from new users on how Python variables work wouldn't
> be an issue if they came from a Scheme background.  The idea of names
> and binding of names would make perfect sense to them.

Of course. But that's because they would have suffered the same confusion
when learning Scheme, and got past it by their second language, Python.






[1] I'm choosing this word carefully. People claim all sorts of things.


-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
h

Re: Why not allow empty code blocks?

2016-07-30 Thread Gregory Ewing

Steven D'Aprano wrote:

In English,
we can talk about having a quick meal of fast food, but not a fast meal of
quick food.


If you interpret "quick" in its original sense of "alive"
then it's theoretically possible, although not practised
much in civilised society these days. Yoghurt might
qualify, though.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Gregory Ewing

Chris Angelico wrote:

I mean, "for i in 3.5" should start half way down the loop body, complete that 
loop, and
then do three complete loops.


+1, this is the best idea for a "loop-and-a-half"
construct I've ever seen.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Rustom Mody
On Sunday, July 31, 2016 at 7:07:45 AM UTC+5:30, Gregory Ewing wrote:
> Michael Torrie wrote:
> > Python would have been alright to teach "programming," but to
> > teach the actual theory of programming languages (lambda calculus, lists
> > as a foundation unit for all other data structures)
> 
> I wouldn't say that "lists as a foundation unit for all other
> data structures" is (or should be) part of the fundamental theory
> of programming languages.
> 
> It seems to me that Python's notions of sequences and mappings
> are much more general and elegant theoretical elements to build
> on.

A key component of a fundamental theory of computation is the idea of
a universal data structure.

For a turing machine its the tape that can carry data or another TM to make
a UTM (UNIVERSAL turing machine)

For a von Neumann machine its the memory that is impartial to whether its 
holding data or code  (as against Harvard architecture)
https://en.wikipedia.org/wiki/Harvard_architecture#Contrast_with_von_Neumann_architectures

For Gödel's theorem it is humonguous integers which can ‘carry’ plain ol’ 
integers or theorems, proofs and effectively ‘the whole world’ via the
Gödel-numbering:
https://en.wikipedia.org/wiki/G%C3%B6del_numbering

At the other end of the spectrum is Lisp whose S-expression is likewise
universal and can be effectively used for carrying the whole theory much more
elegantly than Turing more elegantly than Gödel:
http://www.diku.dk/~neil/comp2book2007/book-whole.pdf

From a software engineering pov, yes one can encode any data structure as
arbitrary length integers. It works as data structure but its a horrible.
This is the Gödel approach

By cutting up the humonguous number into small squares on a tape, Turing’s 
approach is more tractable. Its still clumsy because it requires parsing.

Structure the tape as a tree and this nuisance vanishes.
This Lisp/S-exp/Neil-Jones cleanest of all solutions is like everything else in
our field least known.

Of course one could argue that mapping is somehow more universal than list.
[I have often pondered this question]
ie one can represent
[a,b,c]
as
{0:a, 1:b, 2:c}

Still, whatever is chosen, one needs one single data structure (or more 
correctly data type) to carry the whole world.

Lists PLUS Mappings will not do

[Note I am not talking software engineering but requirements for a complete 
theory]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sun, Jul 31, 2016 at 11:45 AM, Gregory Ewing
 wrote:
> Chris Angelico wrote:
>>
>> So do I need to be able to "call a function as if it
>> were a procedure", or is there a stark difference between the two
>> types of callable?
>
>
> Well, Pascal makes a stark distinction between them -- it's
> a compile-time error to call a procedure as though it were
> a function or vice versa in Pascal -- and it didn't seem to
> cause any great problems.
>
> So it's at least possible to write useful code under such
> circumstances, and it might even help to catch certain
> classes of errors. But the ability to ignore return values
> can be useful as well. Most languages since have decided
> not to make the distinction, and don't seem to have
> suffered noticeably as a result.

Yeah. The distinction means you have a fundamental API difference
between the procedures (which don't return anything) and the functions
(whose return values you mightn't care about). It means you can't
upgrade something from "always returns None" to "returns the number of
objects frobbed" without breaking compat. Conversely, if you decide
that any function can be called "as a procedure" (this is what REXX
does, for instance), then you've just merged the two types of callable
and distinguished them only in usage.

Personally, I don't see any value to the distinction at all.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sun, 31 Jul 2016 04:46 am, BartC wrote:

> On 30/07/2016 16:48, Steven D'Aprano wrote:
>> On Sat, 30 Jul 2016 11:58 pm, BartC wrote:
>>
>>> The 'i' is superfluous. Why not:
>>>
>>>   for 10:
>>
>> Why bother? What's so special about this that it needs dedicated syntax?
> 
> No named loop variable to invent, create, maintain, and destroy. No
> range object to create, destroy etc. If you're looking for ways for a
> language to be more efficient, then why disregard this possibility?

Who says I've disregarded it? Just because I've concluded that the benefit
fails to outweigh the costs doesn't mean I didn't think about it.

To be clear, it's not *my* decision whether or not Python gets this new
syntactic feature or that. But the same applies to the people (mostly
Guido) whose decision it is. Just because they come to the opposite
conclusion to you doesn't mean they haven't considered alternatives.


[...]
> But I'm sure you have needed, at
> some time or other, infinite loops or repeat N times loops. And then you
> just emulate them as best you can with 'while 1:' or 'for _ in
> range(N):' or whatever.

"As best you can" sounds second best. How about we say *better* instead?

"while True" doesn't merely emulate an infinite loop, it implements an
infinite loop without needing dedicated syntax, byte-code or
implementation. Infinite loops are not conceptually different from finite
loops, they're just ordinary while loops where the condition is always
true.

If you say to me that a dedicated infinite loop construct can save a
comparison each time round, I'll have two responses:

(1) That's close to the worst example of premature optimization I've ever
seen. Outside of artificial and trivial benchmarks involving do-nothing or
do-almost-nothing loops, in what real-world situation is the difference
between:

do forever:  # no comparison made
block

and

do while True  # always checks that the constant True is, in fact, True
block

going to be significant? The *MOST* you are going to save will be a
conditional test (in Python, that will probably be based on a pointer
comparison, or something equivalently cheap) before the jump.


(2) And even if it is significant, surely that's something that a keyhole
optimizer can detect without requiring the user to care one iota about the
difference? And indeed, that's EXACTLY what Python 3.6 (and probably older
versions) does: it optimizes out the comparison, and unconditionally loops:

py> from dis import dis
py> dis("while flag: spam()")
  1   0 SETUP_LOOP  14 (to 16)
>>2 LOAD_NAME0 (flag)
  4 POP_JUMP_IF_FALSE   14
  6 LOAD_NAME1 (spam)
  8 CALL_FUNCTION0 (0 positional, 0 keyword pair)
 10 POP_TOP
 12 JUMP_ABSOLUTE2
>>   14 POP_BLOCK
>>   16 LOAD_CONST   0 (None)
 18 RETURN_VALUE
py> dis("while True: spam()")
  1   0 SETUP_LOOP  10 (to 12)
>>2 LOAD_NAME0 (spam)
  4 CALL_FUNCTION0 (0 positional, 0 keyword pair)
  6 POP_TOP
  8 JUMP_ABSOLUTE2
 10 POP_BLOCK
>>   12 LOAD_CONST   0 (None)
 14 RETURN_VALUE


 
> But dedicated forms (even if they just map to 'while' or 'for') wouldn't
> hurt. Syntax is free after all, and it's about expressing exactly what
> you mean.

Syntax is not free!

Syntax requires more code in the compiler. Somebody has to write it,
somebody has to maintain it, somebody has to test it, somebody has to
document it.

When you offer a choice between two or more features which do the same
thing, say a general case and a dedicated special case, your users have to
learn them both. They have to understand the difference between them, and
they have to choose which to use. And they invariably have to deal with
code by others which chooses "wrongly" according to the user's own values.

Every little feature increases the size of the compiler, both the source and
binary, and increases the chances of compiler bugs. There are already
situations where compilers are too big (e.g. on embedded devices, or
memory- and storage-constrained machines like the RaspberryPy). It adds to
the time it takes to download, adds to the time it takes to build the
compiler, adds to the time to test the compiler, and adds to the time it
takes to compile your code. It increases the compiler complexity, and
having dedicated opcodes may rule out certain JIT optimization strategies.

You're perfectly welcome to decide that you consider those costs to be
negligible, especially for a language that has a user-base of one, namely
yourself. That's your value judgement. Others may judge differently.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org

Re: Why not allow empty code blocks?

2016-07-30 Thread Gregory Ewing

Chris Angelico wrote:

So do I need to be able to "call a function as if it
were a procedure", or is there a stark difference between the two
types of callable?


Well, Pascal makes a stark distinction between them -- it's
a compile-time error to call a procedure as though it were
a function or vice versa in Pascal -- and it didn't seem to
cause any great problems.

So it's at least possible to write useful code under such
circumstances, and it might even help to catch certain
classes of errors. But the ability to ignore return values
can be useful as well. Most languages since have decided
not to make the distinction, and don't seem to have
suffered noticeably as a result.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Gregory Ewing

Michael Torrie wrote:

Python would have been alright to teach "programming," but to
teach the actual theory of programming languages (lambda calculus, lists
as a foundation unit for all other data structures)


I wouldn't say that "lists as a foundation unit for all other
data structures" is (or should be) part of the fundamental theory
of programming languages.

It seems to me that Python's notions of sequences and mappings
are much more general and elegant theoretical elements to build
on.

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


usage of functools.partial in in parallelism

2016-07-30 Thread Sivan Greenberg
Hi all,

 I'm wondering about the use of partial in writing parallel code. Is is it
quicker than re-evaluating arguments for a multiple session.get()'s method
with different , for example (of requests) ?

 Or maybe it is used to make sure the arguments differ per each invocation
? (the parallel invocation is supposedly using tasks / co-routine support
in Python 3.

 I can't publish the code I spotted that in.

 What are ups and downs of using them when are they in context?

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


Re: Why not allow empty code blocks?

2016-07-30 Thread BartC

On 30/07/2016 17:15, Rustom Mody wrote:

On Saturday, July 30, 2016 at 8:17:19 PM UTC+5:30, Steven D'Aprano wrote:

On Sat, 30 Jul 2016 09:39 pm, Rustom Mody wrote:


On Saturday, July 30, 2016 at 4:56:01 PM UTC+5:30, Chris Angelico wrote:

On Sat, Jul 30, 2016 at 8:15 PM, BartC wrote:

Anyway, if you're going to talk about annoying things forced upon you
by the language, what about:

"()" in "print (x)" for Python 3


Why are you singling out print? It's just a function like any other.
Are you complaining about the way function calls need parentheses?


Its a function… ok.
Its ‘just’ a function… Arguable


"Granny Weatherwax, you are a natural-born disputant."
"I ain't!"


Heh I really aint :D
At least not for this dispute — its not my baby
Or rather its a stepbaby of stepbaby

Diff between
print "x"
and
print("x")
is one char — the closing ‘)’

To make a dispute about that — I’ll leave to BartC!


I'll try to oblige...

The difference between the space and "(" is significant to those who 
can't type! (Or have some difficulty in using a keyboard for any reason. 
Or are trying to eat lunch at the same time.)


A space bar is nice and fat, and doesn't need shifting.

Yes you have to make the effort in most code to type shifted 
punctuation, but there it's worth doing. With 'print', you might be 
adding and removing such statements hundreds of times so that extra 
effort is wasted.


(The situation is worse in C however, where, if you want to even 
temporarily print out two labelled values, it's:


  printf("A= %d, B= %d\n", a, b);

for something that might have a half-life of 20 seconds (it might take 
longer to type it out!). In Python 3 it would be:


  print ("A=", a, "B=", b)

so it's much nicer even with parentheses. So the point I'm making is 
minor. On the other hand, elsewhere I normally type:


  cpl =a, =b

('cpl' is an alias for 'println'. The '=' operator is a gimmick which 
automatically produces a label prefix, so this is equivalent to:


  println "A=", a, "B=", b

))

--
Bartc



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


Re: Why not allow empty code blocks?

2016-07-30 Thread BartC

On 30/07/2016 16:48, Steven D'Aprano wrote:

On Sat, 30 Jul 2016 11:58 pm, BartC wrote:


The 'i' is superfluous. Why not:

  for 10:


Why bother? What's so special about this that it needs dedicated syntax?


No named loop variable to invent, create, maintain, and destroy. No 
range object to create, destroy etc. If you're looking for ways for a 
language to be more efficient, then why disregard this possibility?



Hypertalk (and related XTalk languages) offer a number of dedicated looping
constructs. Using square brackets [] for optional terms:

repeat [forever]
repeat [for] number [times]
repeat until condition
repeat while condition
repeat with variable = start [to] end
repeat with variable = start [down to] end


That's right, a bare "repeat" on its own gives you an infinite loop. Does
*your* language have special syntax for infinite loops? If not, why not?


The infinite loop is:  do ... od

However, there aren't multiple statements here, but just one. The full 
syntax is:


   for i:=A to B by C when D do ... [else...] od

but some parts are optional. So for example:

   for i to B do ... od  # loop from i=1 to B
 to N do ... od  # repeat N times
  do ... od  # repeat forever
   for i:=A   do ... od  # loop from i=A forever

My syntax was based on Algol68 where there is only one loop form and 
it's something like this IIRC:


   for i:=A to B by C while D do ... od

By leaving out the first parts, you end up with a while-loop! So this 
gives you all the possibilities (except repeat ... until/while which is 
missing from the language.).


(In Algol68, a false value in 'while D' will terminate the loop. The 
'when D' condition in my version will only skip that iteration.


But I have a dedicated 'while' loop as well. As has Python. Note that 
the for-loops above iterate only over integers. I use 'forall' for what 
Python calls a for-loop.)



We should accept that some things are just a matter of taste and idiom. When
I wrote code in Hypertalk, I used those six different forms and found them
perfectly reasonable *in that language*. When I write Python code, I never
find myself wishing I could write Hypertalk code repeat loops (not since
1998 or thereabouts) in Python, since they don't "feel" right for the
language: at best, it would be like suddenly dropping into Lolcat in the
middle of an ordinary English sentence. Good for a giggle, but that's all.


Well, they wouldn't work for a start. But I'm sure you have needed, at 
some time or other, infinite loops or repeat N times loops. And then you 
just emulate them as best you can with 'while 1:' or 'for _ in 
range(N):' or whatever.


But dedicated forms (even if they just map to 'while' or 'for') wouldn't 
hurt. Syntax is free after all, and it's about expressing exactly what 
you mean.



--
Bartc

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


Re: Why not allow empty code blocks?

2016-07-30 Thread BartC

On 30/07/2016 18:11, D'Arcy J.M. Cain wrote:



Maybe you should just change it to I_Am_a_Troll@nowhere.  It's becoming
increasingly obvious that you have absolutely no interest in Python and
are just trying to get a rise out of people.


Calm down. I enjoy programming language design and especially like 
discussing syntax.


That's all.


--
Bartc

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


Re: Float

2016-07-30 Thread eryk sun
On Sat, Jul 30, 2016 at 4:03 PM, Dennis Lee Bieber
 wrote:
> And in a rather convoluted route, one can get to the underlying
> representation...
>
 import struct
 f = struct.pack(">f", 3.0)
 i = struct.pack(">i", 3)
 fi = struct.unpack(">i", f)
 ii = struct.unpack(">i", i) #really a waste of time
 "0x%8.8X 0x%8.8X" % (fi[0], ii[0])
> '0x4040 0x0003'

A CPython float is a C double-precision float ('d'), which is an IEEE
754 binary64 on all of CPython's supported platforms. This format has
a precision of 15 decimal digits (rounded down from 15.95). Uniquely
representing a C double requires 17 decimal digits. See the following
Wikipedia article for more information:

https://en.wikipedia.org/wiki/Double-precision_floating-point_format

The underlying representation of 3.0 is as follows:

>>> n = 3.0
>>> hex(struct.unpack('Q', struct.pack('d', n))[0])
'0x4008'

You can confirm this by attaching a native debugger (such as gdb on
Linux or cdb on Windows) and pointer casting the float object's
ob_fval field as a uint64_t integer:

Linux (python3-dbg):

>>> id(n)
140737353618480
(gdb) p/x *(uint64_t *)&((PyFloatObject *)140737353618480)->ob_fval
$1 = 0x4008

Windows (python_d.exe):

>>> id(n)
2398135104848
0:000> ?? *(ULONG64 *)&((PyFloatObject *)2398135104848)->ob_fval
unsigned int64 0x4008`

We can break this down as follows:

sign = 0x400 >> 11
= 0
exponent = (0x400 & (1 << 11 - 1)) - 1023
= 1
significand = 1 + 0x8 / 2 ** 52
= 1.5
n = (-1) ** sign * significand * 2 ** exponent
= 3.0

Python's float type has a hex() method that represents the value in
hexadecimal as follows:

>>> n.hex()
'0x1.8p+1'

This format shows the implicit integer bit of the normalized
significand and decodes the sign and exponent values for you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Michael Torrie
On 07/30/2016 11:53 AM, Steven D'Aprano wrote:
> On Sun, 31 Jul 2016 02:29 am, Rustom Mody wrote:
> 
>> MIT on practical reasons for python over scheme:
>>
> https://www.wisdomandwonder.com/link/2110/why-mit-switched-from-scheme-to-python
>> Berkeley on fundamental reasons for the opposite choice:
>> https://people.eecs.berkeley.edu/~bh/proglang.html
> 
> Not a very useful discussion. His argument basically boils down to:
> 
> "Lisp came up with some good ideas that were copied by other languages.
> Therefore Lisp is a good teaching language."

Maybe.  Lisp and Scheme are great languages to teach the theory of
programming with because they are so easy to use to build DSLs (all
within the same syntax as Lisp), and it kind of acts like a
meta-language.  I'll never use Scheme again in my life, but I'm very
glad to have learned it in my Theory of Programming Languages course at
uni.  Python would have been alright to teach "programming," but to
teach the actual theory of programming languages (lambda calculus, lists
as a foundation unit for all other data structures), Scheme was an ideal
choice for teaching these fundamentals.  The continued confusion that
pops up on the list from new users on how Python variables work wouldn't
be an issue if they came from a Scheme background.  The idea of names
and binding of names would make perfect sense to them.

I remember using Scheme the class to build a full object-oriented
language out of Scheme parts.  Was pretty interesting to create your own
syntactic sugar right in the language itself.

I think they use a version of Scheme called Racket now.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sun, 31 Jul 2016 02:29 am, Rustom Mody wrote:

> MIT on practical reasons for python over scheme:
>
https://www.wisdomandwonder.com/link/2110/why-mit-switched-from-scheme-to-python
> Berkeley on fundamental reasons for the opposite choice:
> https://people.eecs.berkeley.edu/~bh/proglang.html

Not a very useful discussion. His argument basically boils down to:

"Lisp came up with some good ideas that were copied by other languages.
Therefore Lisp is a good teaching language."



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Rustom Mody
On Saturday, July 30, 2016 at 10:45:23 PM UTC+5:30, Chris Angelico wrote:
> On Sun, Jul 31, 2016 at 2:58 AM, Rustom Mody wrote:
> >> Where, in any useful production code, is the difference between
> >> functions and procedures actually helpful? Or where, in student code,
> >> would it be useful to distinguish? I've been teaching Python to
> >> students with a variety of backgrounds, and nobody has yet been
> >> bothered by this. Not a single one.
> >>
> >> ChrisA
> >
> > In English — and all Indo-European¹ languages — there are two moods
> > “It is raining” is in declarative mood
> > “Come in!” is in imperative mood
> >
> > Now there is a realm in which they are not distinct
> >
> > “It is raining!” said Harry Potter to Hermione and it started raining
> > “Come in!” said Harry, And the chair walked hoppety-hop into the room
> >
> > So sure if you want to teach magic to your kids, all power to you.
> > Myself, I’ll stick to what I know better than magic — programming
> 
> Answer the question, maybe... when *in programming* is this
> distinction important?


eg 1
We can write am assignment in a loop
Can we write a loop in an assignment like?
x = while x ...

Less interesting answer — No we cannot
More pertinent — In our zany new language we are inventing we are going to 
allow this.
Ok...
What will it mean?

eg 2
A function can
- return a constant
- a variable
- more generally an expression

How about returning a while loop?

In short you use the imperative-declarative distinction every day all the time 
every line of code that you write.

Some languages reify that as an expression/statement function/procedure
division — Pascal.

But even if your language does not support that reification you would not be
able to write a single line of correct code without it.

Broadly (and simplistically):
- When you ask a question — condition of if or while — you need a declarative 
entity
- When you do an action — assignment, body of if/loop — you need an imperative
entity
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sun, Jul 31, 2016 at 2:58 AM, Rustom Mody  wrote:
>> Where, in any useful production code, is the difference between
>> functions and procedures actually helpful? Or where, in student code,
>> would it be useful to distinguish? I've been teaching Python to
>> students with a variety of backgrounds, and nobody has yet been
>> bothered by this. Not a single one.
>>
>> ChrisA
>
> In English — and all Indo-European¹ languages — there are two moods
> “It is raining” is in declarative mood
> “Come in!” is in imperative mood
>
> Now there is a realm in which they are not distinct
>
> “It is raining!” said Harry Potter to Hermione and it started raining
> “Come in!” said Harry, And the chair walked hoppety-hop into the room
>
> So sure if you want to teach magic to your kids, all power to you.
> Myself, I’ll stick to what I know better than magic — programming

Answer the question, maybe... when *in programming* is this
distinction important?

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


Re: Why not allow empty code blocks?

2016-07-30 Thread D'Arcy J.M. Cain
On Sat, 30 Jul 2016 16:14:18 +0100
BartC  wrote:
> > By the way, the last time I replied to you it went to the list but
> > your address bounced.  Was that a glitch or are you using an
> > invalid address in a mailing list?
> 
> Do you mean my email address? That was valid once but no longer. (If
> you want to send an email replace "bc" with "bcas".)

Are you kidding me?  It's not our job to replace things in your email
address, it's yours.  Fix your client.

> I'm not using a mailing list; I'm posting to usenet.

I don't care if you are using carrier pigeon.  If you send an email
address, make it a valid one.

Maybe you should just change it to I_Am_a_Troll@nowhere.  It's becoming
increasingly obvious that you have absolutely no interest in Python and
are just trying to get a rise out of people.

*plonk*

-- 
D'Arcy J.M. Cain
System Administrator, Vex.Net
http://www.Vex.Net/ IM:da...@vex.net
VoIP: sip:da...@vex.net
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Rustom Mody
On Saturday, July 30, 2016 at 10:07:59 PM UTC+5:30, Chris Angelico wrote:
> On Sun, Jul 31, 2016 at 2:15 AM, Rustom Mody  wrote:
> > Diff between
> > print "x"
> > and
> > print("x")
> > is one char — the closing ‘)’
> >
> > To make a dispute about that — I’ll leave to BartC!
> >
> > The more general baby that is significant is that beginners should have
> > it easy to distinguish procedure and function and python does not naturally 
> > aid that.  print was something procedure-ish in python2 but the general 
> > notion being
> > absent is a much more significant problem (for beginners) than print.
> 
> But Py2's print is not just a procedure. It's magical syntax. You
> can't create your own procedures.
> 
> Why SHOULD they be special? Ultimately, a procedure is simply a
> function that has no useful return value; and there are myriad times
> when I've called a function or method for its side effects and ignored
> the return value. So do I need to be able to "call a function as if it
> were a procedure", or is there a stark difference between the two
> types of callable?
> 
> Where, in any useful production code, is the difference between
> functions and procedures actually helpful? Or where, in student code,
> would it be useful to distinguish? I've been teaching Python to
> students with a variety of backgrounds, and nobody has yet been
> bothered by this. Not a single one.
> 
> ChrisA

In English — and all Indo-European¹ languages — there are two moods
“It is raining” is in declarative mood
“Come in!” is in imperative mood

Now there is a realm in which they are not distinct

“It is raining!” said Harry Potter to Hermione and it started raining
“Come in!” said Harry, And the chair walked hoppety-hop into the room

So sure if you want to teach magic to your kids, all power to you.
Myself, I’ll stick to what I know better than magic — programming

¹ Benjamin Lee Whorf pointed out that fundamental categories — in this example,
imperative and declarative moods — determine the form of thinking of the
people/race that use that language.
In particular the native American language Hopi, is not so ruined with
time-as-space metaphors.  And therefore ‘advanced’ ideas like quantum physics
turn out not so advanced in Hopi [I am told]
But this is all way too far afield
Pragmatically not distinguishing imperative and declarative — or ‘do’ vs ‘is’ 
— is unrealistic
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sun, 31 Jul 2016 12:47 am, Steven D'Aprano wrote:

> On Sat, 30 Jul 2016 09:39 pm, Rustom Mody wrote:
[...]
>> - Prior Art: Its builtin and special in Fortran, Pascal, Basic
> 
> Possibly Fortran. But which version of Fortran? Do we really want to take
> decisions made in 1953 for the first ever high-level language as the
> epitome of good design?

Oops, I meant 1957.





-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sun, Jul 31, 2016 at 2:15 AM, Rustom Mody  wrote:
> Diff between
> print "x"
> and
> print("x")
> is one char — the closing ‘)’
>
> To make a dispute about that — I’ll leave to BartC!
>
> The more general baby that is significant is that beginners should have
> it easy to distinguish procedure and function and python does not naturally 
> aid that.  print was something procedure-ish in python2 but the general 
> notion being
> absent is a much more significant problem (for beginners) than print.

But Py2's print is not just a procedure. It's magical syntax. You
can't create your own procedures.

Why SHOULD they be special? Ultimately, a procedure is simply a
function that has no useful return value; and there are myriad times
when I've called a function or method for its side effects and ignored
the return value. So do I need to be able to "call a function as if it
were a procedure", or is there a stark difference between the two
types of callable?

Where, in any useful production code, is the difference between
functions and procedures actually helpful? Or where, in student code,
would it be useful to distinguish? I've been teaching Python to
students with a variety of backgrounds, and nobody has yet been
bothered by this. Not a single one.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sun, Jul 31, 2016 at 1:48 AM, Steven D'Aprano  wrote:
> Hypertalk (and related XTalk languages) offer a number of dedicated looping
> constructs. Using square brackets [] for optional terms:
>
> repeat [forever]
> repeat [for] number [times]
> repeat until condition
> repeat while condition
> repeat with variable = start [to] end
> repeat with variable = start [down to] end
>
>
> That's right, a bare "repeat" on its own gives you an infinite loop. Does
> *your* language have special syntax for infinite loops? If not, why not?

Hmm, very similar to REXX, with one critical difference. Here's REXX's loops:

do
do forever
do number
do while condition
do until condition
do variable = start [to end] [by step] [for count]

In REXX, "do forever" is like Hypertalk's "repeat forever", and the
other constructs are similar (though the counted form is more flexible
- you can say "do i=1 to 10" to set the end marker, or you can say "do
i=1 for 10" to set an iteration count) - but "do" on its own means
"execute this block of code exactly once", not an infinite loop.
(do/end in this form is for defining blocks of code, like Pascal's
begin/end or C's { }.) Curious distinction.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Rustom Mody
On Saturday, July 30, 2016 at 9:45:34 PM UTC+5:30, Rustom Mody wrote:
> Ok Python is better than Java is better than C++
> But it cannot stand up to scheme as a teaching language
> [The MIT Profs who replaced scheme by python admit to as much viz.

Send pressed prematurely — Sorry

MIT on practical reasons for python over scheme:
https://www.wisdomandwonder.com/link/2110/why-mit-switched-from-scheme-to-python
Berkeley on fundamental reasons for the opposite choice:
https://people.eecs.berkeley.edu/~bh/proglang.html

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


Re: JSON result parsing

2016-07-30 Thread Ben Bacarisse
TUA  writes:

> Calls to my REST api may either return a dict (for single results) or
> a list of dicts (for multiple results).

I think John's answer missed this part.

> I receive these results using the requests library.
>
> I want to retrieve the value for a key 'ID' but only if I have a
> single result and, obviously, if ID is present.

If r is the result of the request, just testing

  if 'ID' in r: ... whatever ...

would do.  The result will be False if r is a list or the single result
does not have an ID.

> How can I do this with pythonic elegance?

Ah, that I leave to others.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Rustom Mody
On Saturday, July 30, 2016 at 8:17:19 PM UTC+5:30, Steven D'Aprano wrote:
> On Sat, 30 Jul 2016 09:39 pm, Rustom Mody wrote:
> 
> > On Saturday, July 30, 2016 at 4:56:01 PM UTC+5:30, Chris Angelico wrote:
> >> On Sat, Jul 30, 2016 at 8:15 PM, BartC wrote:
> >> > Anyway, if you're going to talk about annoying things forced upon you
> >> > by the language, what about:
> >> >
> >> > "()" in "print (x)" for Python 3
> >> 
> >> Why are you singling out print? It's just a function like any other.
> >> Are you complaining about the way function calls need parentheses?
> > 
> > Its a function… ok.
> > Its ‘just’ a function… Arguable
> 
> "Granny Weatherwax, you are a natural-born disputant."
> "I ain't!"

Heh I really aint :D
At least not for this dispute — its not my baby
Or rather its a stepbaby of stepbaby

Diff between
print "x"
and
print("x")
is one char — the closing ‘)’

To make a dispute about that — I’ll leave to BartC!

The more general baby that is significant is that beginners should have
it easy to distinguish procedure and function and python does not naturally aid 
that.  print was something procedure-ish in python2 but the general notion being
absent is a much more significant problem (for beginners) than print.

Brings me to the even more general baby

> 
> 
> > For example:
> > 
> > - Prior Art: Its builtin and special in Fortran, Pascal, Basic
> 
> Possibly Fortran. But which version of Fortran? Do we really want to take
> decisions made in 1953 for the first ever high-level language as the
> epitome of good design?

That comment assumes that things in 1953 were somehow worse than today
This is the general religious commitment to progress
And anyone who questions it is heretical

As for 1953 Ive no idea — I was not there (Fortran came in 57)
But I studied in the 80s and there was greater clarity (about some matters
of course) than now.
eg It was completely natural that in ‘school’ one studied 
‘nice’ things like Pascal, Lisp, Prolog, Snobol, APL etc
And in a professional context used ‘real’ things like 
Fortran, Cobol, PL-1 and a little later C.

Once omnibus languages like C++, Java, C# and Python became popular
the academic vs real-world division has disappeared.
So beginners start with these ‘real-world’
And get their brains scrambled
And think it wonderful

Ok Python is better than Java is better than C++
But it cannot stand up to scheme as a teaching language
[The MIT Profs who replaced scheme by python admit to as much viz.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sat, 30 Jul 2016 11:06 pm, Steven D'Aprano wrote:

> If it a sign of a poor programmer that
> ignores the common idioms of a language and writes in another
> language's "grammar".

/face-palm

"If it a sign..."

Of course that was not intentional. What's the law that says that any post
complaining about somebody else's spelling or grammatical errors will
contain an even worse example of the same? Sod's Law, or a special case of
such.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sun, 31 Jul 2016 12:16 am, BartC wrote:

> On 30/07/2016 14:06, Steven D'Aprano wrote:
> 
>> End of story. As far as I am concerned, the 97% of languages which allow
>> the visual structure of the code to differ from their logical structure
>> are BAD LANGUAGES.
> 
> You mean languages that allow code like this:
> 
> a = (
> b
>   +c *
> 
> 
> d)
> 
> ?

Touché :-)


But the layout of an expression is not really what I'm referring to. The
whitespace between terms in an expression is meaningless. Yes, the example
you give is particularly ugly, but it's no different from:

a = (   b  +c *   d)

on one line. Allowing parentheses to cross over line boundaries is a case of
Practicality Over Purity: there are simply far too many cases where we
want, *need*, a single expression to go over two or more lines, and the
original solution (use a line continuation backslash) wasn't good enough.

I'm referring to flow control elements (if...else, for, while, try...except,
etc), plus a handful of other grouping elements (def, class, with). That's
what I call "logical structure" of the code, not incidental whitespace
between terms of a single expression.

Unfortunately, there's sometimes a conflict between these disparate wants. I
want the logical structure to be obvious; I want the freedom to arrange
expressions over multiple lines. Sometimes they conflict, in which case, I
do my best not to write ugly code. I'd be reluctant to prohibit expressions
from starting at the left of the current indent:

# This should always be allowed
def func():
# current indent aligns here
result = (
  long expression
  over multiple lines
  )
return result


# But this moves to the left of the current indent
def func():
# current indent aligns here
result = (
long expression
over multiple lines
)
return result



I don't like that second case very much at all, but I wouldn't prohibit it,
because I've found too many real world cases where I have big expressions
(say, a table of values) where I need all the space I can get and need to
visually outdent it without logically outdenting it. Its an ugly compromise
between my otherwise very strict view, but that's life for you.


> Another category is where code is written predominantly side-ways rather
> than vertically. (Multiple chained method calls for example, or trying
> to express something as a 'one-liner'.)

I don't see the relevance. If you are writing a chain of method calls, its a
single expression. There's no structure to express.

As for one-liners, Python simply doesn't consider it important or necessary
to support writing arbitrary one-liners. There's some limited support for
the simple cases:

python -c "for x in range(100): print(x**2)"

but beyond that, you have to use multiple lines.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sat, 30 Jul 2016 11:58 pm, BartC wrote:

> The 'i' is superfluous. Why not:
> 
>   for 10:

Why bother? What's so special about this that it needs dedicated syntax?

Hypertalk (and related XTalk languages) offer a number of dedicated looping
constructs. Using square brackets [] for optional terms:

repeat [forever]
repeat [for] number [times]
repeat until condition
repeat while condition
repeat with variable = start [to] end
repeat with variable = start [down to] end


That's right, a bare "repeat" on its own gives you an infinite loop. Does
*your* language have special syntax for infinite loops? If not, why not?


We should accept that some things are just a matter of taste and idiom. When
I wrote code in Hypertalk, I used those six different forms and found them
perfectly reasonable *in that language*. When I write Python code, I never
find myself wishing I could write Hypertalk code repeat loops (not since
1998 or thereabouts) in Python, since they don't "feel" right for the
language: at best, it would be like suddenly dropping into Lolcat in the
middle of an ordinary English sentence. Good for a giggle, but that's all.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread BartC

On 30/07/2016 15:39, D'Arcy J.M. Cain wrote:


By the way, the last time I replied to you it went to the list but your
address bounced.  Was that a glitch or are you using an invalid address
in a mailing list?


Do you mean my email address? That was valid once but no longer. (If you 
want to send an email replace "bc" with "bcas".)


I'm not using a mailing list; I'm posting to usenet.

--
Bartc


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


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sat, 30 Jul 2016 10:31 pm, Rustom Mody wrote:

> What makes you think I wanted to print those numbers??

The fact that you called print.


> Maybe I wanted a list of 10 None-s??

The idiomatic Python way of doing it would be:

[None]*10

The beginner's way of doing it would be:

[None, None, None, None, None, None, None, None, None, None]

The premature optimizer would do the same as the beginner.

Somebody who thinks of list comprehensions as the only hammer in their
toolbox would write:

[None for i in range(10)]

Confused Lisp programmers would write:

list(map(lambda ignore_me: None, range(10)))


But the idea that somebody might call print(i), and put up with its HIGHLY
VISIBLE side-effects, just for the return result of None, instead of just
writing None, is too implausible to take seriously. If I saw such code, I'd
immediately submit it to The Daily WTF.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sat, 30 Jul 2016 10:27 pm, BartC wrote:

> This is one thing I can never get right in Python: controlling when a
> newline is or isn't generated and what happens with separators.

In Python 3, that's easy: the default space separator and newline at the end
can both be customized to any string you like:

print(x, y, z, sep=' +++ ', end='\n\tEND\n')

individually or together, including the empty string:

print(x, y, z, sep='\n', end='')

And naturally, since these are just ordinary function arguments, they are
restricted to constant literals. They can be variables or expressions:

print(x, y, z, end=(get_output_end() or OUTPUT_END))



[...]
> (Some languages use 'write' or 'writeln', or 'print' or 'println'; what
> could be simpler? Or you just explicitly output a "\n" string.)

One function is simpler than two, so print() with explicit keyword arguments
is obviously simpler AND more powerful.


 

-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sat, 30 Jul 2016 09:39 pm, Rustom Mody wrote:

> On Saturday, July 30, 2016 at 4:56:01 PM UTC+5:30, Chris Angelico wrote:
>> On Sat, Jul 30, 2016 at 8:15 PM, BartC wrote:
>> > Anyway, if you're going to talk about annoying things forced upon you
>> > by the language, what about:
>> >
>> > "()" in "print (x)" for Python 3
>> 
>> Why are you singling out print? It's just a function like any other.
>> Are you complaining about the way function calls need parentheses?
> 
> Its a function… ok.
> Its ‘just’ a function… Arguable

"Granny Weatherwax, you are a natural-born disputant."
"I ain't!"


> For example:
> 
> - Prior Art: Its builtin and special in Fortran, Pascal, Basic

Possibly Fortran. But which version of Fortran? Do we really want to take
decisions made in 1953 for the first ever high-level language as the
epitome of good design?

Pascal? There is no "print" in standard Pascal, there are a pair of
procedures writeln() and write().

Early BASIC has a built-in print statement, but BASIC had very little
facility for functions or procedures. *Every* built-in command
was "special" to a language where you used GOTO and GOSUB instead of
functions.

And in any case, Python's print is a built-in, so it is *just as special* as
Fortran, Pascal and BASIC versions.


> - More immediate : It was a special in python2

It was *too* special in Python 2.

Being a statement, there's nothing you can do with it except use it
directly. You can't pass it to another function, or use it as a callback,
or apply functools.partial to it, or monkeypatch it. When people proposed
adding new functionality to it, the ability to print to a file, instead of
adding a simple keyword argument, the actual grammar of the language had to
be changed to support a hideously ugly variant:

print >>file, args

If Python had originally been a function, and somebody proposed making it a
statement, what do you think the chances are that proposal would be
accepted? Some design decisions are simply bad ideas, and making print a
statement was one of them.


> - Poorer error catching: What was a straight syntax error is now a
> lint-catch (at best)
>   [print (x) for x in range(20)]

Using a list comprehension just for the side effects is *poor practice* but
legal. Besides, perhaps print() has been monkey-patched to return a useful
value, which you wish to collect in a list.

Its not the compiler's job to decide what is and isn't good code. There are
an infinite number of things a programmer can do which is "poor practice".
Should we try to make them all syntax errors?

# Calculate x plus ten.
y = x + 1
y = y + 1
y = y + 1
y = y + 1
y = y + 1
y = y + 1
y = y + 1
y = y + 1
y = y + 1
y = y + 1
y = y + 1
y = y - 1  # Oops, we went too far, go back one.


Should we insist that Python must have a "add 10" statement, and forbid the
plus operator, so that poor quality code like the above will be a syntax
error?

# new and improved special syntax
addten x as y


print never should have been a statement. Being a built-in function is
special enough.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread D'Arcy J.M. Cain
On Sat, 30 Jul 2016 11:15:12 +0100
BartC  wrote:
>> Doesn't it look like there's something missing in the Python? Both
> the 'fi' or 'end', and the possibility of an 'h' statement.
> 
> Note the Algol68-style style is more free-format where indents are
> not significant.
> 
> Anyway, if you're going to talk about annoying things forced upon you
> by the language, what about:
> 
> ":" after "else"
> 
> "()" in "def fn():"
> 
> "()" in "print (x)" for Python 3
> 
> "for i in range(N):" just to repeat a block N times...
> 
> That's apart from the obligatory indents which, with an
> 'end'-delimited scheme, are not always necessary.

Has it occurred to you (as it has occurred to some of us) that Python
just isn't your language?

By the way, the last time I replied to you it went to the list but your
address bounced.  Was that a glitch or are you using an invalid address
in a mailing list?

-- 
D'Arcy J.M. Cain
System Administrator, Vex.Net
http://www.Vex.Net/ IM:da...@vex.net
VoIP: sip:da...@vex.net
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread BartC

On 30/07/2016 14:06, Steven D'Aprano wrote:


End of story. As far as I am concerned, the 97% of languages which allow the
visual structure of the code to differ from their logical structure are BAD
LANGUAGES.


You mean languages that allow code like this:

a = (
   b
 +c *


d)

?

Another category is where code is written predominantly side-ways rather 
than vertically. (Multiple chained method calls for example, or trying 
to express something as a 'one-liner'.)


--
Bartc


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


Re: Why not allow empty code blocks?

2016-07-30 Thread BartC

On 30/07/2016 14:36, Chris Angelico wrote:

On Sat, Jul 30, 2016 at 11:06 PM, Steven D'Aprano  wrote:

"for i in range(N):" just to repeat a block N times...


Why should there be special syntax just for repeating a block N times?
There's a general purpose for-loop which performs iteration. Why do you
need special syntax to do what it already does?


>
> Python could have chosen to make integers iterable, such that you say:
>
> for i in 10:
>
> but I don't think it really improves readability.

On 30/07/2016 13:47, Chris Angelico wrote:
>(Also, it requires the use
> and damage of some iterator variable, which may be significant in some
> contexts.)

The 'i' is superfluous. Why not:

 for 10:

(In my own syntaxes I use (actual example):

  to 64 do
  table append:= nextbyte(fs)
  od

Python equivalent:

  for i in range(64):
  table.append(nextbyte(fs))

The range object isn't really necessary, and the 'i' variable doesn't 
need to be exposed (as a programmer-accessible, reference-counted variable).


The 'to' construct I also implemented with a single very fast byte-code, 
executed once per iteration.)



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


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sat, Jul 30, 2016 at 11:06 PM, Steven D'Aprano  wrote:
>> "for i in range(N):" just to repeat a block N times...
>
> Why should there be special syntax just for repeating a block N times?
> There's a general purpose for-loop which performs iteration. Why do you
> need special syntax to do what it already does?

Python could have chosen to make integers iterable, such that you say:

for i in 10:

but I don't think it really improves readability. It wouldn't
materially damage the language, though - the 'for' loop still does
exactly what it does, the rules are still just as simple. The only
question would be: why can't floats be iterable too? I mean, "for i in
3.5" should start half way down the loop body, complete that loop, and
then do three complete loops.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Steven D'Aprano
On Sat, 30 Jul 2016 08:15 pm, BartC wrote:

> Interesting use of 'pass' in this example:
> 
> http://pastebin.com/aYJdgEL4
> 
> (I do believe he's using 'pass' as 'end'! Although he misses some out in
> that case.)

I wouldn't call it so much "interesting" as "a good example of how not to
program".

All languages -- human and programming -- involve certain quirks, or
features which are matters of taste. If it a sign of a poor programmer that
ignores the common idioms of a language and writes in another
language's "grammar".

"If so smart Yoda is, how come English speak he cannot?"

People are more forgiving off grammatical errors and weird idioms than
computer programs, but still, there are conventions to follow. In English,
we can talk about having a quick meal of fast food, but not a fast meal of
quick food. Our computers are powerful, never mighty, and if we ever invent
a time machine, we'll travel into the past, not onto the past.

You can get away with breaking a language's idioms for humour:

https://www.youtube.com/watch?v=MNyG-xu-7SQ

or, if you're *really* talented, as art. See, for example, James Joyce's
Finnegan's Wake, which is as unidiomatic as it is possible to be while
still being (just barely) English, but deliberately so.

(As opposed to "ee cummings", who was and is lauded far beyond his actual
talent.)

Th same principles apply to programming languages. But outside of highly
optimized code, which is often ugly, or examples of code as art (like code
golf, Obfuscated C and Underhanded C competitions, multi-language hybrid
code, esoteric languages etc.), the aim of programming should be to
maximize *human* communication. And that usually means writing in the
idiomatic style of the natives. There are no awards for trying to hammer
the round pegs of Algol grammar into the square holes of the Python
interpreter.

(1) Using "pass" as a form of "end" is simply bizarre.

(2) Python allows the semi-colon for the convenience of command-line users,
where it is sometimes difficult to write multiple lines of code. Using it
inside a .py file is a sign of somebody who is not a native speaker.

(3) Separating statements by variable numbers of spaces, between 1 and 13 by
my count, is just weird.

Given the lack of Python fluency, the lack of documentation and meaningful
comments, the unusual (for Python) idioms that hurt readability, and some
very odd names (there is one constant called "ONE" with the value
1073741824), the overall impression I get is that the author of that file
simply isn't a good programmer.


[...]
> As I've mentioned, Python also uses explicit block delimiters in the
> form of else, elif, except, finally (and whichever ones I've misssed):


You are wrong. They are not delimiters. They *begin* a new block, they don't
end the previous one except as a side effect of beginning a new block.

if condition:
block
new block

It is the dedent (outdent) that ends the if block. "new block" is permitted
to be an elif or else statement, of course, but you cannot write:


if condition:
block
else: statement

because "else" is not an "end of if" statement. It *begins* a new statement.


>   if x: a; b elif y: c; d elif z: e; f else: g

That's not legal Python syntax.


> In the above syntax, it would be:
> 
>   if x then a; b elsif y then c; d elsif z then e; f else g fi
> 
> Doesn't it look like there's something missing in the Python? 

No it does not.



> Both the 
> 'fi' or 'end', and the possibility of an 'h' statement.
> 
> Note the Algol68-style style is more free-format where indents are not
> significant.

Good for Algol. To my eyes, that makes it harder to read: too many
unneeded "ends", to great a risk that the visual structure of the code
doesn't match the logical structure of the code.


> Anyway, if you're going to talk about annoying things forced upon you by
> the language, what about:
> 
> ":" after "else"

What about it? When you write a list of items in English, it is more
idiomatic and natural to end the clause with a semi-colon:

- item one
- item two
- item three


than without it.

I've read Cobra code which is very like Python except (among other changes)
they've dropped the semi-colons It simply looks wrong Like sentences
without punctuation Or perhaps like an painting on a wall just every so
slightly on an angle


> "()" in "def fn():"

I could go either way with that.


> "()" in "print (x)" for Python 3

Why? Do you object to other functions using parentheses?


> "for i in range(N):" just to repeat a block N times...

Why should there be special syntax just for repeating a block N times?
There's a general purpose for-loop which performs iteration. Why do you
need special syntax to do what it already does?

We have a general "if" clause for doing conditional branching. Would you
insist on a special purpose if syntax for testing if a number is 2?

if number == 1:  # general case
if number == 7921  # general case
iftwo number:  # special syntax


> That's apar

Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sat, Jul 30, 2016 at 10:47 PM, Chris Angelico  wrote:
> So, no improvement - exactly equal. And no longer a single expression,
> ergo no longer valid in as many contexts. (Also, it requires the use
> and damage of some iterator variable, which may be significant in some
> contexts.)

In case it's not clear: 

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sat, Jul 30, 2016 at 10:39 PM, BartC  wrote:
> On 30/07/2016 13:22, Chris Angelico wrote:
>
> print(*range(10), sep='\n')
>>
>> 0
>> 1
>> 2
>> 3
>> 4
>> 5
>> 6
>> 7
>> 8
>> 9
>
>
>>
>> Beat that, print statement.
>
>
> for i in range(10): print i
>
> Same number of characters, but a lot less punctuation!

So, no improvement - exactly equal. And no longer a single expression,
ergo no longer valid in as many contexts. (Also, it requires the use
and damage of some iterator variable, which may be significant in some
contexts.)

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sat, Jul 30, 2016 at 10:31 PM, Rustom Mody  wrote:
> What makes you think I wanted to print those numbers??
> Maybe I wanted a list of 10 None-s??

Because you NEVER SAID what you wanted! How can you talk about error
detection if you won't say what the programmer's intention was? You're
forcing us to guess, and then complaining that I guessed wrongly.

> Point being that when one mixes up 2 things like that its anybody’s guess
> which is the primary (central) effect and which the ‘side’ effect

Okay, so my revised guess is: Console output is a primary effect and
should not have a secondary effect of returning None. Great. Now
please go and build yourself a language in which list.append is a
statement (because it shouldn't return None either), etc, etc, just in
case someone uses them wrongly. I'll keep using Python, where it's
normal for a side-effect-y function to return None - it's much
simpler. And even in Pike, where void functions are a real thing, it's
possible to recast the function so you can call it in an expression
context - and the same thing happens. Truly void functions are nothing
but parser convenience.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread BartC

On 30/07/2016 13:22, Chris Angelico wrote:


print(*range(10), sep='\n')

0
1
2
3
4
5
6
7
8
9




Beat that, print statement.


for i in range(10): print i

Same number of characters, but a lot less punctuation!

--
Bartc

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Rustom Mody
On Saturday, July 30, 2016 at 5:53:12 PM UTC+5:30, Chris Angelico wrote:
> On Sat, Jul 30, 2016 at 10:11 PM, Rustom Mody  wrote:
> >> > - Poorer error catching: What was a straight syntax error is now a 
> >> > lint-catch (at best)
> >> >   [print (x) for x in range(20)]
> >>
> >> Huh? Aside from the fact that you're constructing a useless list of
> >> Nones, what's the error?
> >
> > Huh²
> >
> > Are you seriously suggesting that python-3’s behavior below is better IN
> > THIS INSTANCE than python-2’s?
> >
> > [That there may be other reasons that outweigh this one for 
> > print-as-function
> > is not something I am disputing. I was solely disputing your ‘just’]
> >
> > Python 2.7.12 (default, Jul  1 2016, 15:12:24)
>  [print(x) for x in range(10)]
> >   File "", line 1
> > [print(x) for x in range(10)]
> >  ^
> > SyntaxError: invalid syntax
> 
> >
> > Python 3.5.2 (default, Jul  5 2016, 12:43:10)
> >
>  [print(x) for x in range(10)]
> > 0
> > 1
> > 2
> > 3
> > 4
> > 5
> > 6
> > 7
> > 8
> > 9
> > [None, None, None, None, None, None, None, None, None, None]
> 
> 
> I still don't understand your complaint. How is this "better/worse
> error checking"? All you're showing me is the same line of code you
> showed above, plus what it does in Py2 and Py3, which I know already.
> You haven't explained why this is such a great feature in Py2 that got
> lost in Py3.
> 
> And hey. If you want to print out the numbers 0 through 9, Py3 offers
> a pretty concise way to spell that:
> 
> >>> print(*range(10), sep='\n')

Heh Cute! Thanks!!

> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> >>>
> 
> Beat that, print statement.

What makes you think I wanted to print those numbers??
Maybe I wanted a list of 10 None-s??

Point being that when one mixes up 2 things like that its anybody’s guess
which is the primary (central) effect and which the ‘side’ effect
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sat, Jul 30, 2016 at 10:27 PM, BartC  wrote:
>> where the print function allows full customization
>> of both end= and sep=.
>
>
> This is one thing I can never get right in Python: controlling when a
> newline is or isn't generated and what happens with separators.
>
> (In fact when I used Python as a target language, I had to generate calls to
> sys.stdout.write instead as it had more predictable behaviour.)
>
> So if it's the advantage of using () then it's one I never benefit from!
>
> Newline control should be one of the simplest things in the language, part
> of the very first programs you write.
>
> (Some languages use 'write' or 'writeln', or 'print' or 'println'; what
> could be simpler? Or you just explicitly output a "\n" string.)

Here, look:

print(obj) # with newline
print(obj, end="") # without newline

Easy, isn't it?

Start playing to the language's strengths instead of fighting against
them. Keyword arguments are a Python feature that I frequently yearn
for in other languages. Use them!

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


Re: Why not allow empty code blocks?

2016-07-30 Thread BartC

On 30/07/2016 12:49, Chris Angelico wrote:

On Sat, Jul 30, 2016 at 9:39 PM, Rustom Mody  wrote:



Its a function… ok.
Its ‘just’ a function… Arguable

For example:

- Prior Art: Its builtin and special in Fortran, Pascal, Basic


And it's not built-in or special in C, or a bunch of other languages.


The parentheses are a nuisance in C too, as are obligatory format codes. 
And C created a lot of bad precedences (literally in the case of binary 
operators!)


For an informal, rapid development language, the less formality about 
these things the better.



- More immediate : It was a special in python2


Which resulted in unmitigatable problems, such as that you can't mock
it for testing or redirection purposes,


The language finds other solutions so that programs using "print A" 
don't need changing. Perhaps 'print ' is syntactic sugar for 
'_print (' or something.


 and it demands syntactic magic

to do its work - for instance, the only option is a "soft space" in
place of a newline, where the print function allows full customization
of both end= and sep=.


This is one thing I can never get right in Python: controlling when a 
newline is or isn't generated and what happens with separators.


(In fact when I used Python as a target language, I had to generate 
calls to sys.stdout.write instead as it had more predictable behaviour.)


So if it's the advantage of using () then it's one I never benefit from!

Newline control should be one of the simplest things in the language, 
part of the very first programs you write.


(Some languages use 'write' or 'writeln', or 'print' or 'println'; what 
could be simpler? Or you just explicitly output a "\n" string.)


--
Bartc


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


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sat, Jul 30, 2016 at 10:11 PM, Rustom Mody  wrote:
>> > - Poorer error catching: What was a straight syntax error is now a 
>> > lint-catch (at best)
>> >   [print (x) for x in range(20)]
>>
>> Huh? Aside from the fact that you're constructing a useless list of
>> Nones, what's the error?
>
> Huh²
>
> Are you seriously suggesting that python-3’s behavior below is better IN
> THIS INSTANCE than python-2’s?
>
> [That there may be other reasons that outweigh this one for print-as-function
> is not something I am disputing. I was solely disputing your ‘just’]
>
> Python 2.7.12 (default, Jul  1 2016, 15:12:24)
 [print(x) for x in range(10)]
>   File "", line 1
> [print(x) for x in range(10)]
>  ^
> SyntaxError: invalid syntax

>
> Python 3.5.2 (default, Jul  5 2016, 12:43:10)
>
 [print(x) for x in range(10)]
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> [None, None, None, None, None, None, None, None, None, None]


I still don't understand your complaint. How is this "better/worse
error checking"? All you're showing me is the same line of code you
showed above, plus what it does in Py2 and Py3, which I know already.
You haven't explained why this is such a great feature in Py2 that got
lost in Py3.

And hey. If you want to print out the numbers 0 through 9, Py3 offers
a pretty concise way to spell that:

>>> print(*range(10), sep='\n')
0
1
2
3
4
5
6
7
8
9
>>>

Beat that, print statement.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Rustom Mody
On Saturday, July 30, 2016 at 5:19:25 PM UTC+5:30, Chris Angelico wrote:
> On Sat, Jul 30, 2016 at 9:39 PM, Rustom Mody  wrote:
> > On Saturday, July 30, 2016 at 4:56:01 PM UTC+5:30, Chris Angelico wrote:
> >> On Sat, Jul 30, 2016 at 8:15 PM, BartC wrote:
> >> > Anyway, if you're going to talk about annoying things forced upon you by 
> >> > the
> >> > language, what about:
> >> >
> >> > "()" in "print (x)" for Python 3the modulo operator
> >>
> >> Why are you singling out print? It's just a function like any other.
> >> Are you complaining about the way function calls need parentheses?
> >
> > Its a function… ok.
> > Its ‘just’ a function… Arguable
> >
> > For example:
> >
> > - Prior Art: Its builtin and special in Fortran, Pascal, Basic
> 
> And it's not built-in or special in C, or a bunch of other languages.
> 
> > - More immediate : It was a special in python2
> 
> Which resulted in unmitigatable problems, such as that you can't mock
> it for testing or redirection purposes, and it demands syntactic magic
> to do its work - for instance, the only option is a "soft space" in
> place of a newline, where the print function allows full customization
> of both end= and sep=. The print function is DEFINITELY an
> improvement. I would also posit that an sprintf() built-in function
> instead of str.__mod__ would have meant there was less kickback
> against printf-style formatting, because it wouldn't have had the
> strange behaviour around single-argument use. (It's pretty simple to
> write, of course, but built-ins are extremely significant to
> perception. def sprintf(fmt, *args): return fmt % args) Syntax is NOT
> always an improvement.
> 
> > - Poorer error catching: What was a straight syntax error is now a 
> > lint-catch (at best)
> >   [print (x) for x in range(20)]
> 
> Huh? Aside from the fact that you're constructing a useless list of
> Nones, what's the error?

Huh²

Are you seriously suggesting that python-3’s behavior below is better IN
THIS INSTANCE than python-2’s?

[That there may be other reasons that outweigh this one for print-as-function 
is not something I am disputing. I was solely disputing your ‘just’]

Python 2.7.12 (default, Jul  1 2016, 15:12:24) 
>>> [print(x) for x in range(10)]
  File "", line 1
[print(x) for x in range(10)]
 ^
SyntaxError: invalid syntax
>>> 

Python 3.5.2 (default, Jul  5 2016, 12:43:10) 

>>> [print(x) for x in range(10)]
0
1
2
3
4
5
6
7
8
9
[None, None, None, None, None, None, None, None, None, None]
>>> 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Float

2016-07-30 Thread Chris Angelico
On Sat, Jul 30, 2016 at 9:44 PM, Cai Gengyang  wrote:
> You mentioned that : A floating point number[2] is number that is not an 
> integer (and not a
> complex number)
>
> Hence ,
>
> 10 is not a floating point number because it is an integer
> 25 is not a floating point number because it is an integer
> 7 + 3i is not a floating number because it is a complex number
> 8 + 5i is not a floating number because it is a complex number.
>
> Is 3.0 a floating number ? It is a rational number, not an integer right ?

In a computing context, data types are incredibly significant. So yes,
3.0 *is* a floating-point number. It's equal to the integer 3, because
they represent the same number, but it's not identical to it. You can
convert from one to the other with the built-ins int and float:

>>> 3.0 == 3
True
>>> int(3.0)
3
>>> float(3)
3.0

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sat, Jul 30, 2016 at 9:39 PM, Rustom Mody  wrote:
> On Saturday, July 30, 2016 at 4:56:01 PM UTC+5:30, Chris Angelico wrote:
>> On Sat, Jul 30, 2016 at 8:15 PM, BartC wrote:
>> > Anyway, if you're going to talk about annoying things forced upon you by 
>> > the
>> > language, what about:
>> >
>> > "()" in "print (x)" for Python 3the modulo operator
>>
>> Why are you singling out print? It's just a function like any other.
>> Are you complaining about the way function calls need parentheses?
>
> Its a function… ok.
> Its ‘just’ a function… Arguable
>
> For example:
>
> - Prior Art: Its builtin and special in Fortran, Pascal, Basic

And it's not built-in or special in C, or a bunch of other languages.

> - More immediate : It was a special in python2

Which resulted in unmitigatable problems, such as that you can't mock
it for testing or redirection purposes, and it demands syntactic magic
to do its work - for instance, the only option is a "soft space" in
place of a newline, where the print function allows full customization
of both end= and sep=. The print function is DEFINITELY an
improvement. I would also posit that an sprintf() built-in function
instead of str.__mod__ would have meant there was less kickback
against printf-style formatting, because it wouldn't have had the
strange behaviour around single-argument use. (It's pretty simple to
write, of course, but built-ins are extremely significant to
perception. def sprintf(fmt, *args): return fmt % args) Syntax is NOT
always an improvement.

> - Poorer error catching: What was a straight syntax error is now a lint-catch 
> (at best)
>   [print (x) for x in range(20)]

Huh? Aside from the fact that you're constructing a useless list of
Nones, what's the error?

Also: Why is print special here? Maybe you accidentally called
frobnicate on those x's and you shouldn't have. How is Python supposed
to know that that's an error?

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


Re: Float

2016-07-30 Thread Cai Gengyang

You mentioned that : A floating point number[2] is number that is not an 
integer (and not a 
complex number)

Hence ,

10 is not a floating point number because it is an integer
25 is not a floating point number because it is an integer 
7 + 3i is not a floating number because it is a complex number 
8 + 5i is not a floating number because it is a complex number.

Is 3.0 a floating number ? It is a rational number, not an integer right ?









On Saturday, July 30, 2016 at 6:34:25 PM UTC+8, Steven D'Aprano wrote:
> On Sat, 30 Jul 2016 08:21 pm, Cai Gengyang wrote:
> 
> > Cool ... can you give a concrete example ?
> 
> A concrete example of a float?
> 
> I already gave two:
> 
> 
> >> Python floats use 64 bits (approximately 18 decimal digits). Because the
> >> decimal point can "float" from place to place, they can represent very
> >> small numbers:
> >> 
> >> 1.2345678901234567e-100
> >> 
> >> and very big numbers:
> >> 
> >> 1.2345678901234567e100
> 
> 
> Here are some more:
> 
> 0.5  # one half
> 0.25  # one quarter
> 7.5  # seven and a quarter
> 0.001  # one thousandth
> 
> 12345.6789
> # twelve thousand, three hundred and forty-five, point six seven eight nine
> 
> -1.75  # minus one point seven five
> 0.0  # zero
> 3.0  # three
> 
> 1.23e45  # one point two three times ten to the power of forty-five
> 
> 
> 
> 
> -- 
> Steven
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread Rustom Mody
On Saturday, July 30, 2016 at 4:56:01 PM UTC+5:30, Chris Angelico wrote:
> On Sat, Jul 30, 2016 at 8:15 PM, BartC wrote:
> > Anyway, if you're going to talk about annoying things forced upon you by the
> > language, what about:
> >
> > "()" in "print (x)" for Python 3
> 
> Why are you singling out print? It's just a function like any other.
> Are you complaining about the way function calls need parentheses?

Its a function… ok.
Its ‘just’ a function… Arguable

For example:

- Prior Art: Its builtin and special in Fortran, Pascal, Basic
- More immediate : It was a special in python2
- Poorer error catching: What was a straight syntax error is now a lint-catch 
(at best)
  [print (x) for x in range(20)]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why not allow empty code blocks?

2016-07-30 Thread Chris Angelico
On Sat, Jul 30, 2016 at 8:15 PM, BartC  wrote:
> Anyway, if you're going to talk about annoying things forced upon you by the
> language, what about:
>
> "()" in "print (x)" for Python 3

Why are you singling out print? It's just a function like any other.
Are you complaining about the way function calls need parentheses?

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


Re: Zero runtime impact tracing

2016-07-30 Thread Steven D'Aprano
On Sat, 30 Jul 2016 06:32 pm, Johannes Bauer wrote:

> Hi group,
> 
> I'm using CPython 3.5.1. Currently I'm writing some delicate code that
> is doing the right thing in 99% of the cases and screws up on the other
> 1%.
> 
> I would like to have tracing in some very inner loops:
> 
> if self._debug:
>print("Offset %d foo bar" % (self._offset))
> 
> However, this incurs a hefty performance penalty even when tracing
> disabled.

Without seeing your code, it's hard to say. My guess is that you can
optimize this slightly:

class X:
def method(self):
debug = bool(self._debug)  # force a bool, just in case
for value in sequence:
# critical loop
if debug:
print("Offset %d foo bar" % (self._offset))
...


That saves an attribute lookup and *potentially* a bool conversion each time
around the loop.

If that's still too slow, just about the fastest thing you can do is Python
is an "is" comparison against None. Try this:

class X:
def method(self):
if self._debug:
   sentinel = None
else:
   sentinel = object()  # Anything except None. 
for value in sequence:
# critical loop
if sentinel is None:
print("Offset %d foo bar" % (self._offset))
...


Of course, it's even faster to NOT do a comparison:


class X:
def method(self):
if self._debug:
for value in sequence:
# critical loop
print("Offset %d foo bar" % (self._offset))
...
else:
for value in sequence:
# critical loop
...


although that duplicates code. If the body of the loop is only small, say
two or three lines at most, you might not mind that it is duplicated.


> What I want is that the if clause completely disappears during bytecode
> compilation if self._debug is not set. Is there any way that I can tell
> the optimizer that this variable will either be set once, but never
> change during runtime and that it can go ahead and completely remove the
> code when self._debug is False?

No. However, you can get a similar result using the magic dunder variable
__debug__ (that's TWO leading and trailing underscores):


class X:
def method(self):
for value in sequence:
# critical loop
if __debug__:
print("Offset %d foo bar" % (self._offset))
...


In that case, the byte-code generated will be equivalent to the critical
loop:

for value in sequence:
# critical loop
print("Offset %d foo bar" % (self._offset))
...

with no test, unless you pass -O as a command-line option to Python, in
which case both the test and the call to print will be completely removed:

for value in sequence:
# critical loop
...



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Float

2016-07-30 Thread Steven D'Aprano
On Sat, 30 Jul 2016 08:21 pm, Cai Gengyang wrote:

> Cool ... can you give a concrete example ?

A concrete example of a float?

I already gave two:


>> Python floats use 64 bits (approximately 18 decimal digits). Because the
>> decimal point can "float" from place to place, they can represent very
>> small numbers:
>> 
>> 1.2345678901234567e-100
>> 
>> and very big numbers:
>> 
>> 1.2345678901234567e100


Here are some more:

0.5  # one half
0.25  # one quarter
7.5  # seven and a quarter
0.001  # one thousandth

12345.6789
# twelve thousand, three hundred and forty-five, point six seven eight nine

-1.75  # minus one point seven five
0.0  # zero
3.0  # three

1.23e45  # one point two three times ten to the power of forty-five




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Float

2016-07-30 Thread Cai Gengyang
Cool ... can you give a concrete example ?

On Friday, July 29, 2016 at 10:27:08 PM UTC+8, Steven D'Aprano wrote:
> On Fri, 29 Jul 2016 07:44 pm, Cai Gengyang wrote:
> 
> > Can someone explain in layman's terms what "float" means ?
> 
> Floating point number:
> 
> https://en.wikipedia.org/wiki/Floating_point
> 
> As opposed to fixed point numbers:
> 
> https://en.wikipedia.org/wiki/Fixed-point_arithmetic
> 
> Python floats use 64 bits (approximately 18 decimal digits). Because the
> decimal point can "float" from place to place, they can represent very
> small numbers:
> 
> 1.2345678901234567e-100
> 
> and very big numbers:
> 
> 1.2345678901234567e100
> 
> using just 64 bits. If it were *fixed* decimal place, the range would be a
> lot smaller: for example, suppose the decimal place was fixed after three
> digits. The largest number would be 999.999 and the smallest
> would be 0.001.
> 
> 
> 
> 
> -- 
> Steven
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-30 Thread BartC

On 30/07/2016 04:35, Steven D'Aprano wrote:

On Sat, 30 Jul 2016 06:19 am, BartC wrote:


The language requires that blocks always contains 1 or more statements.
Fair enough, except that 0 statements are often needed


They really aren't.

The standard library uses more "pass" statements than most code I've seen,
because of the large number of abstract methods and tests that use dummy
classes or methods. If you are writing library code, or a framework, with
lots of "do nothing" blocks that the caller is supposed to override, you
may find yourself doing the same. Even so, the number of "pass" statements
is a tiny proportion of code, less than one percent for Python 3.6:

[steve@ando Lib]$ wc -l *.py */*.py | tail -n 1
  541022 total
[steve@ando Lib]$ grep "pass$" *.py */*.py | wc -l
3286


Over two thirds of them are from the test suite:

[steve@ando Lib]$ grep "pass$" test/*.py | wc -l
2270


Interesting use of 'pass' in this example:

http://pastebin.com/aYJdgEL4

(I do believe he's using 'pass' as 'end'! Although he misses some out in 
that case.)





I feel confident in saying that if you find yourself writing "pass" in
application code (as opposed to writing a framework or unit tests for a
library) more than one time in a 500 lines of code, you're doing something
wrong. But even if it were as high as one time in 100 lines, it is still
not an onerous requirement.

You should see how many times Ruby programmers have to write "end", 99.9% of
which are unneeded but forced on them by the language.


Think of it as a pattern. In one language, I used (Algol68-style), a 
simple if was:


  if a then b else c fi

which could also be written more compactly, as suits an expression:

  ( a | b | c )

Then the 'fi' (that is, 'end' or 'end if') is just closing the construct 
started with 'fi', in the same way that ')' closes the opening '('.


As I've mentioned, Python also uses explicit block delimiters in the 
form of else, elif, except, finally (and whichever ones I've misssed):


 if x: a; b elif y: c; d elif z: e; f else: g

In the above syntax, it would be:

 if x then a; b elsif y then c; d elsif z then e; f else g fi

Doesn't it look like there's something missing in the Python? Both the 
'fi' or 'end', and the possibility of an 'h' statement.


Note the Algol68-style style is more free-format where indents are not 
significant.


Anyway, if you're going to talk about annoying things forced upon you by 
the language, what about:


":" after "else"

"()" in "def fn():"

"()" in "print (x)" for Python 3

"for i in range(N):" just to repeat a block N times...

That's apart from the obligatory indents which, with an 'end'-delimited 
scheme, are not always necessary.


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


Re: Zero runtime impact tracing

2016-07-30 Thread Ned Batchelder
On Saturday, July 30, 2016 at 4:32:25 AM UTC-4, Johannes Bauer wrote:
> Hi group,
> 
> I'm using CPython 3.5.1. Currently I'm writing some delicate code that
> is doing the right thing in 99% of the cases and screws up on the other 1%.
> 
> I would like to have tracing in some very inner loops:
> 
> if self._debug:
>print("Offset %d foo bar" % (self._offset))
> 
> However, this incurs a hefty performance penalty even when tracing disabled.
> 
> What I want is that the if clause completely disappears during bytecode
> compilation if self._debug is not set. Is there any way that I can tell
> the optimizer that this variable will either be set once, but never
> change during runtime and that it can go ahead and completely remove the
> code when self._debug is False?
> 
> Any other means of signalling the it should compile the tracing code in
> would also be fine by me (e.g, calling Python with some command line
> options or such). As long as during normal operation, there is no
> performance impact.

The __debug__ name is a constant defined by the setting of the -O
command-line switch, and will be compiled away if not true:

https://docs.python.org/3/library/constants.html#__debug__

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


Zero runtime impact tracing

2016-07-30 Thread Johannes Bauer
Hi group,

I'm using CPython 3.5.1. Currently I'm writing some delicate code that
is doing the right thing in 99% of the cases and screws up on the other 1%.

I would like to have tracing in some very inner loops:

if self._debug:
   print("Offset %d foo bar" % (self._offset))

However, this incurs a hefty performance penalty even when tracing disabled.

What I want is that the if clause completely disappears during bytecode
compilation if self._debug is not set. Is there any way that I can tell
the optimizer that this variable will either be set once, but never
change during runtime and that it can go ahead and completely remove the
code when self._debug is False?

Any other means of signalling the it should compile the tracing code in
would also be fine by me (e.g, calling Python with some command line
options or such). As long as during normal operation, there is no
performance impact.

Cheers,
Johannes

-- 
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
 - Karl Kaos über Rüdiger Thomas in dsa 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: SOAP and Zeep

2016-07-30 Thread dieter
Ethan Furman  writes:
> I may have a need in the immediate future to work with SOAP and WSDL 
> services, and a quick search
> turned up Zeep (http://docs.python-zeep.org/en/latest/) -- does anyone have 
> any experience with it?
> Or any other libraries that can be recommended?

I am using "suds" to access existing WSDL/SOAP services - and I am very
satisfied. No support for the implementation of such services or
for WSDL generation, though.

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


Re: TypeError: '_TemporaryFileWrapper' object is not an iterator

2016-07-30 Thread dieter
Terry Reedy  writes:
> ...
>> The problem seems to come from my expectation that a file
>> is its own iterator and in python3 that is no longer true
>> for a NamedTemporaryFile.
> ...
>> Should this be considered a bug?
>
> No.  The doc for NamedTemporaryFile does not even claim that the
> return is iterable.

I think, it should: the name suggests that "NamedTemporaryFile" is
a "File" and therefore should behave like one.

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