Re: seeking deeper (language theory) reason behind Python design choice

2018-05-08 Thread Chris Angelico
On Wed, May 9, 2018 at 3:44 PM, Steven D'Aprano
 wrote:
> On Tue, 08 May 2018 22:48:52 -0500, Python wrote:
>> I've always felt that this mentality was insulting to the programmer:
>> "You're too stupid to get this right."  Sure, I've created that bug in
>> other languages (or rather its inverse) but not since college.  You make
>> it a few times, you go nuts debugging it, you learn what it is, you
>> never do it again.
>
> And fortunately we don't have to deal with a steady stream of new
> programmers learning the language and making newbie errors, right?
>
> If all programmers were as awesome as you and never made typos, the world
> would be a better place. But we know from experience that even
> experienced C programmers can make this mistake by accident.

Yes, and I'd go further: I *am* too stupid to get this right. That's
why I have an editor that highlights certain words. (My current editor
colours every Python standard library module name, so if I happen to
create a variable called "time", it'll make it really obvious that I
am now shadowing an importable module. Or, as I recently did,
"sched".) That's why Python gives me tracebacks that show me exactly
where I messed up. That's why my code is full of debugging checks,
comments, and other tools to help me track down my mistakes after I
make them.

Because I *will* make mistakes. I will make a LOT of mistakes. And I
am not going to try to pretend that I don't.

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


Re: seeking deeper (language theory) reason behind Python design choice

2018-05-08 Thread Chris Angelico
On Wed, May 9, 2018 at 3:36 PM, Ian Kelly  wrote:
>
> while True:
> if we_are_done():
> break
> # do some stuff
> ...
> if error_occurred():
> break
> notify_user()
>
>
> Fixed, using idiomatic Python and without needing to use assignment in
> an expression.

Why is it that "while True" is idiomatic Python for a non-infinite
loop? Is it merely because Python currently has no other way to spell
certain loops? Surely it would be more idiomatic to encode the loop's
termination condition in the header, if it were possible.

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


Re: seeking deeper (language theory) reason behind Python design choice

2018-05-08 Thread Steven D'Aprano
On Tue, 08 May 2018 22:48:52 -0500, Python wrote:

> On Tue, May 08, 2018 at 12:45:29AM +, Steven D'Aprano wrote:
>> Currently, the real reason is that lambda expressions are limited to a
>> single expression as the body of the function, and binding operations
>> in Python are statements.
> 
> ...which begs the question, why shouldn't assignments be expressions, as
> they are in many other languages?  TBH this is one of the few things
> about Python that I dislike.

No, it raises the question :-) Begging the question means to assume the 
answer to the same question you are asking.

As Chris already pointed out, there is a PEP in progress at the moment 
aimed at allowing assignment expressions (PEP 572). It is very 
controversial, but Guido appears to be in favour of it (as I am, although 
not necessarily in its current form). There's about a bazillion emails on 
the Python-Ideas and Python-Dev mailing lists arguing about it.

(Oh, and it goes *all the way back to February*.)

In the very earliest versions of Python, like 0.1, there was only a 
single = operator that was used for both equals and assignment, but that 
was changed by the first official 1.0 release. I don't know if that 
change was driven by personal preference (Guido just liked it better), 
bad experiences with bugs, or what.

But by the time 1.4 came around, Guido had settled on a clean separation 
between statements and expressions as part of Python's design.

That separation has gradually weakened over the years, with the addition 
of the ternary if operator and comprehensions, but it is still an 
important part of Python's design. You might find something on Guido's 
blogs or his various essays:

http://neopythonic.blogspot.com.au/

https://www.artima.com/weblogs/index.jsp?blogger=guido

https://legacy.python.org/doc/essays/


but I don't have time to go trawling the blogs for this.

It might simply be that Guido (like many people) considered assignment to 
fundamentally be an imperative command, not an expression.

Another reason is something Nick Coghlan (re-)discovered during the 
discussions for PEP 572, namely that if you allow the full, unrestricted 
assignment targets as an expression, the code is ambiguous or at least 
hard to understand the intent. That's why PEP 572 has limited assignments 
to just plain names, and not arbitrary assignment targets. Possibly Guido 
recognised this way back in Python 0.x as well.


>> since = in a statement on its own is not dangerous. People *almost
>> never* intend to write == for the side-effects only:
> 
> Seriously?  I do this--not every day, but more than occasionally, not
> just in Python.
> 
> flag = (spam == arg)

Of course we all do that, but it is nothing like what I said. I even gave 
fully-commented sample code, which you appear to have missed:

# don't care whether they are actually equal or not
# just want to call the __eq__ method for its side-effects
spam == arg + 1

I bet you never, ever, ever call == for the side-effects, throwing away 
the result of the comparison without using it or looking at it in any 
way. In many languages, such a comparison cannot even have side-effects, 
so it would be useless dead code.


>> # don't care whether they are actually equal or not 
>> # just want to call the __eq__ method for its side-effects
>> spam == arg + 1
>> 
>> Since that never happens in real life, there's no risk of accidentally
>> writing "spam = arg + 1" when you wanted "spam == arg + 1".
> 
> I've always felt that this mentality was insulting to the programmer:
> "You're too stupid to get this right."  Sure, I've created that bug in
> other languages (or rather its inverse) but not since college.  You make
> it a few times, you go nuts debugging it, you learn what it is, you
> never do it again.

And fortunately we don't have to deal with a steady stream of new 
programmers learning the language and making newbie errors, right?

If all programmers were as awesome as you and never made typos, the world 
would be a better place. But we know from experience that even 
experienced C programmers can make this mistake by accident.

Or deliberately:

https://freedom-to-tinker.com/2013/10/09/the-linux-backdoor-attempt-
of-2003/

or if that URL wraps: https://tinyurl.com/jpvbtua


Of course we all make mistakes, but some features and syntax are bug 
magnets: they *encourage* errors rather than discourage them. Anyone can 
mistype "flga" when they meant "flag", but the use of real words 
discourages that error since the reader can see that "flga" looks weird. 
But == and = are so similar that not only is it an easy typo to make, but 
its a hard typo to spot without a close, careful reading.


-- 
Steve

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


Re: Problem/bug with class definition inside function definition

2018-05-08 Thread Gregory Ewing

Alexey Muranov wrote:

   x = 42

   class C:
   x = x  # Works


I'd say it kind of works by accident, and is not really an
intended feature.

if Python does not allow to refer "simultaneously" to 
variables from different scopes if they have the same name.


It seems perfectly reasonable to me to have to use different
names to refer to different things in the same context. :-)

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


Re: seeking deeper (language theory) reason behind Python design choice

2018-05-08 Thread Ian Kelly
On Tue, May 8, 2018 at 9:48 PM, Python  wrote:
> On Tue, May 08, 2018 at 12:45:29AM +, Steven D'Aprano wrote:
>> since = in a statement on its own is not dangerous. People *almost never*
>> intend to write == for the side-effects only:
>
> Seriously?  I do this--not every day, but more than occasionally, not
> just in Python.
>
> flag = (spam == arg)
> vs.
> if spam == arg:
> flag = True
> else:
> flag = False
> if flag:
> do_something()
> else:
> do_something_else()

As Chris pointed out, this is not an example of using == for side-effects only.

>> # don't care whether they are actually equal or not
>> # just want to call the __eq__ method for its side-effects
>> spam == arg + 1
>>
>> Since that never happens in real life, there's no risk of accidentally
>> writing "spam = arg + 1" when you wanted "spam == arg + 1".
>
> I've always felt that this mentality was insulting to the programmer:
> "You're too stupid to get this right."  Sure, I've created that bug in
> other languages (or rather its inverse) but not since college.  You
> make it a few times, you go nuts debugging it, you learn what it is,
> you never do it again.
>
> And, this kind of thing is what code reviews are for--Python isn't so
> idiot-proof that you can get away without doing them for any
> non-trivial code--so (IMO) the language should not prevent you from
> doing useful things *simply* because you *might* make a mistake.

I do code reviews every day, and I doubt that I would actually notice
if one of them slipped in '=' where '==' was intended. Hopefully it
would be caught by unit testing though.

>  I'll
> give you an example that is both a case where Python's design choices
> make creating a bug easier, AND a case where allowing assignments to
> be expressions would save you.
>
> flag = we_are_done()
> while not flag:
> # do some stuff
> ...
> if error_occured():
> break
> falg = we_are_done()
> notify_user()
># flag will be checked again later, perhaps for error reporting


while True:
if we_are_done():
break
# do some stuff
...
if error_occurred():
break
notify_user()


Fixed, using idiomatic Python and without needing to use assignment in
an expression.

> Here, a common programming pattern (prime the loop control variable)
> gets you in trouble, because the assignment happens in two places, and
> you mistyped one of them.  There's no syntax error, but your program
> will execute forever, unless you were already done on the first call
> to prime the flag, or an error occurs.  This is probably worse than
> the = vs. == error, because your brain tends to "autocorrect" certain
> kinds of spelling errors, whereas experienced programmers learn to
> look for (or avoid entirely) the assignment vs. comparison bug.  The
> error here is reasonably easy to spot, given the trivial nature of the
> example, but would likely be harder to spot in more complex code with
> longer, more meaningful variable names.
>
> This example also is a case FOR allowing assignments to be
> expressions.  If Python allowed them, you could rewrite this as:
>
>while not (flag = we_are_done()):
> ...
> if error_occured():
> break
>notify_user()
># flag will be checked again later, perhaps for error reporting
>
> This COMPLETELY PREVENTS the spelling bug in the code above, since the
> assignment only happens in one place; and as a bonus it's less code.

Or just use an IDE with variable name autocompletion.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: seeking deeper (language theory) reason behind Python design choice

2018-05-08 Thread Chris Angelico
On Wed, May 9, 2018 at 1:48 PM, Python  wrote:
>> since = in a statement on its own is not dangerous. People *almost never*
>> intend to write == for the side-effects only:
>
> Seriously?  I do this--not every day, but more than occasionally, not
> just in Python.
>
> flag = (spam == arg)
> vs.
> if spam == arg:
> flag = True
> else:
> flag = False
> if flag:
> do_something()
> else:
> do_something_else()

That's not "side effects only". You're evaluating a comparison for its
result - its primary effect. You're assigning the result of the
comparison to something.

Using equality comparisons for side effects would look like this:

spam == arg

No assignment. Just that, as a statement all on its own. It's
perfectly legal, but I doubt you've ever actually done this.

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


Re: seeking deeper (language theory) reason behind Python design choice

2018-05-08 Thread Python
On Tue, May 08, 2018 at 12:45:29AM +, Steven D'Aprano wrote:
> Currently, the real reason is that lambda expressions are limited to a 
> single expression as the body of the function, and binding operations in 
> Python are statements. 

...which begs the question, why shouldn't assignments be expressions,
as they are in many other languages?  TBH this is one of the few
things about Python that I dislike.

> > So far, no satisfying answer has come up, except for maybe to avoid a
> > programmer accidentally typing `=` instead of `==`, which I find a bit
> > unsatisfying as the only reason.
> 
> No, that's the reason why = is a statement not an expression. That's not 
> why statements aren't allowed in lambdas. If we had blocks, this would be 
> perfectly acceptable:
> 
> lambda arg: %%%START BLOCK
> spam = arg + 1
> ...
> %%%END BLOCK
> 
> since = in a statement on its own is not dangerous. People *almost never* 
> intend to write == for the side-effects only:

Seriously?  I do this--not every day, but more than occasionally, not
just in Python.

flag = (spam == arg)
vs.
if spam == arg:
flag = True
else:
flag = False
if flag:
do_something()
else:
do_something_else()

Obviously this is a simple example which could be rewritten and/or the
comparison copy-pasted; assume a more complex system where you need to
check if the two objects were equal in multiple places, but obtaining
the objects is computationally expensive (say, processing a large file
to obtain a large list of objects), and comparing them is likewise
computationally expensive.

> # don't care whether they are actually equal or not
> # just want to call the __eq__ method for its side-effects
> spam == arg + 1
> 
> Since that never happens in real life, there's no risk of accidentally 
> writing "spam = arg + 1" when you wanted "spam == arg + 1".

I've always felt that this mentality was insulting to the programmer:
"You're too stupid to get this right."  Sure, I've created that bug in
other languages (or rather its inverse) but not since college.  You
make it a few times, you go nuts debugging it, you learn what it is,
you never do it again.

And, this kind of thing is what code reviews are for--Python isn't so
idiot-proof that you can get away without doing them for any
non-trivial code--so (IMO) the language should not prevent you from
doing useful things *simply* because you *might* make a mistake.  I'll
give you an example that is both a case where Python's design choices
make creating a bug easier, AND a case where allowing assignments to
be expressions would save you.

flag = we_are_done()
while not flag:
# do some stuff
...
if error_occured():
break
falg = we_are_done()
notify_user()
   # flag will be checked again later, perhaps for error reporting

Here, a common programming pattern (prime the loop control variable)
gets you in trouble, because the assignment happens in two places, and
you mistyped one of them.  There's no syntax error, but your program
will execute forever, unless you were already done on the first call
to prime the flag, or an error occurs.  This is probably worse than
the = vs. == error, because your brain tends to "autocorrect" certain
kinds of spelling errors, whereas experienced programmers learn to
look for (or avoid entirely) the assignment vs. comparison bug.  The
error here is reasonably easy to spot, given the trivial nature of the
example, but would likely be harder to spot in more complex code with
longer, more meaningful variable names.

This example also is a case FOR allowing assignments to be
expressions.  If Python allowed them, you could rewrite this as:

   while not (flag = we_are_done()):
...
if error_occured():
break
   notify_user()
   # flag will be checked again later, perhaps for error reporting

This COMPLETELY PREVENTS the spelling bug in the code above, since the
assignment only happens in one place; and as a bonus it's less code.

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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Steven D'Aprano
On Tue, 08 May 2018 23:16:23 +0300, Mikhail V wrote:

> I don't propose to remove spaces, 

And that is why the syntax will be ambiguous. So long as whitespace is 
*allowed* but not *required* around operators, there will be ambiguity 
between a - b and a - b with no way to tell whether they are intended as 
two items or one.


> but I propose Tab-separated elements.

We already have tab-separated elements in Python. It is allowed to use 
tabs between any whitespace separated tokens.

The only restriction is that in Python 3 you must use *consistent* spaces 
or tabs but not a mix of both for indents.


> If I allow commas as well, this will become not so simple, probably.
> Also I don't propose syntax for e-mail code exchange, but rather syntax
> for *work* an this can potentially help a lot of people in everyday
> work.

/head-desk

You: "I have invented amazing new syntax that cannot be exchanged by 
email. Here, let me email some examples to you."

Do you understand that you have already emailed samples of this proposed 
code?


> Also I don't know what kind of human thinks that this:
>  a + b
>  is two elements "a" and "+ b"
> What is "+ b"? 

It is unary plus followed by b.

If you don't know Python's existing syntax, how can you possibly expect 
to invent new syntax?


> And who writes "- b" with a space in unary minus? I don't. Nobody does.

Oh well, if you don't, then clearly nobody in the world, and no code 
generators, could possibly do it. Because Mikhail says so.


> Is it allowed? yes. no problem.

Since it is allowed, it is a HUGE problem for your syntax, since your 
syntax cannot distinguish between the two cases.


[...]
> There is "invisible" difference in indentations tabs vs spaces - so
> what? 

That means that people will look at a piece of code and not know whether 
they are seeing spaces or tabs, since they are both invisible.


> I don't want spaces or tabs visible - there is toggle "show tabs"
> and "toggle show space" for that

/head-desk

You: "This syntax doesn't need tabs and spaces to be visible. Just use 
the Show Tabs and Show Spaces commands on your editor to make them 
visible."


> Those are basically universal features. And thousands of Python people
> already use tabs to align columns so you have to accept it

Current syntax allows people to use tabs to align columns, and it remains 
unambiguous no matter how wacky people align their data, because of the 
commas. Even if they think they are writing Fortran with fixed column 
widths, it is still unambiguous to both the human reader and the parser:

data = [+   a   ,   -b  ,
-   foo ,   +bar,   ]

even if they separate operators from their operands with tabs. Paste that 
into your Python interpreter, and it has an unambiguous meaning.

The same does not apply to your syntax. Take out the commas, and it is 
impossible to tell what the code means or how many columns it has.


>> Using a particular editor is not and will not be a mandatory
>> requirement for Python.
> 
> Using outdated tools or being PEBCAK are not and will not be
> justification for language syntax improvements.

It is not your choice of what editors people are permitted to use in 
order to read and write Python.


[...]
>> - the first one allows you to write it as a single line:
>>
>> L = ((a, 1), (b, 2), (c, 3), (foobar, 4))
>>
>>   instead of wasting vertical space;
> 
> Wasting space you say? You economize paper for printing out?

No. I arrange code in the best way I see fit, depending on the code. 
Sometimes that means I put things on a single line, so as to fit more 
lines into a single screen, sometimes it means I spread things out over 
multiple lines in order to get maximum benefit from two dimensional 
layout. It all depends on the code I am writing and I use whatever is 
best for the situation.


>> - the first one is unambiguous while the second is ambiguous;
> 
> I think it's time to reveal what exactly you mean here.

For the fourth time, it means that the current syntax is unambiguous and 
only ever has a single meaning. Your suggestion is ambiguous, it cannot 
be parsed into a single meaning, and you have to guess what the code 
possibly means.

A single expression like either of these:

a   +   b

a   +b

under your syntax have TWO legal meanings, and there is no way to tell 
which is required except to guess.

I do not know how to make it more clear.


>> - the first one can include nested data structures, while
>>   the second cannot.
> 
> Why it can't? did you read the original e-mail?

Of course I did. You said:

"To present nesting of elements of higher than 2 levels, 
normal Python syntax can be used for deeper nesting"

and 

"So the idea is to cover only first two levels of 
nesting of course."

With bracket syntax, I can cover unlimited levels of nesting. Yours 
cannot.




-- 
Steve

-- 
https://mail.python.o

Re: Suggestion for a "data" object syntax

2018-05-08 Thread Mikhail V
On Wed, May 9, 2018 at 3:14 AM, Ben Finney  wrote:
> Mikhail V  writes:
>
>> On Wed, May 9, 2018 at 12:33 AM, Chris Angelico  wrote:
>> > On Wed, May 9, 2018 at 7:15 AM, Mikhail V  wrote:
>> >> Just admit it, you try to troll me (or just pretend, I don't know).
>> >
>> > No, I am not trolling you.
>>
>> I don't believe you.
>
> If that's true – if you believe Chris is trolling you – then please do
> not continue the conversation. Since you have already decided Chris is
> trolling you,

Well, the thing is I don't know how exactly the word "trolling" can
be understood by different persons. I use it here in sense of "nitpicking".
Or "fooling around" I don't know actually.
So may be "trolling" has too negative associations to your ears?

As for Chris' attitude in this thread, and my point on this -
well, honestly yes, I believe he uses an opportunity to push
his own game. It has happened before - and now I know already,
so I know that trying to explain and honestly answer his questions ends up
in the same game of Chris - so I suppose he amuses himself
in such a way.
Same scenario happens here - he just completely neglects the whole
proposal straight away with a bold provoking statement.
But then asks "why do you think this a good proposal?"
Which I actually tried to describe in the very proposal.

So honestly I can't understand what game this time he prepared,
and not very much into this kind of things.



>
> This forum has no need of another thread attempting to “win” an argument
> that one side believes is dishonest.
>
> --
>  \   “The best in us does not require the worst in us: Our love of |
>   `\ other human beings does not need to be nurtured by delusion.” |
> _o__) —Sam Harris, at _Beyond Belief 2006_ |
> Ben Finney
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Ben Finney
Mikhail V  writes:

> On Wed, May 9, 2018 at 12:33 AM, Chris Angelico  wrote:
> > On Wed, May 9, 2018 at 7:15 AM, Mikhail V  wrote:
> >> Just admit it, you try to troll me (or just pretend, I don't know).
> >
> > No, I am not trolling you.
>
> I don't believe you.

If that's true – if you believe Chris is trolling you – then please do
not continue the conversation. Since you have already decided Chris is
trolling you, it follows that you will not respond productively to
anything he says to you. So this thread is already lost.

This forum has no need of another thread attempting to “win” an argument
that one side believes is dishonest.

-- 
 \   “The best in us does not require the worst in us: Our love of |
  `\ other human beings does not need to be nurtured by delusion.” |
_o__) —Sam Harris, at _Beyond Belief 2006_ |
Ben Finney

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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Mikhail V
On Wed, May 9, 2018 at 12:33 AM, Chris Angelico  wrote:
> On Wed, May 9, 2018 at 7:15 AM, Mikhail V  wrote:
>> On Tue, May 8, 2018 at 5:25 PM, Chris Angelico  wrote:
>>> On Tue, May 8, 2018 at 10:52 PM, Mikhail V  wrote:
 Right? Your issues with tabs aside, I think it is impossible to ignore the
 the readability improvement. Not even speaking of how
 many commas and bracket you need to type in the first case.
>>>
>>> That's incredibly subjective. Or else straight-up wrong, I'm not sure which.
>>
>> Just admit it, you try to troll me (or just pretend, I don't know).
>
> No, I am not trolling you.

I don't believe you.


> Neither of those examples is program code. You are asking for a
> syntactic change to a *programming language*. Everything you've said
> is fine for a non-code format. Nothing is applicable to a programming
> language.

Everything I said in previous mail was related to your claim that it's
Ok (or even better?) readable
with brackets and commas in a table than without them.
I was not even starting this terminology course.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Mark Lawrence

On 08/05/18 22:33, Chris Angelico wrote:

On Wed, May 9, 2018 at 7:15 AM, Mikhail V  wrote:

On Tue, May 8, 2018 at 5:25 PM, Chris Angelico  wrote:

On Tue, May 8, 2018 at 10:52 PM, Mikhail V  wrote:

Right? Your issues with tabs aside, I think it is impossible to ignore the
the readability improvement. Not even speaking of how
many commas and bracket you need to type in the first case.


That's incredibly subjective. Or else straight-up wrong, I'm not sure which.


Just admit it, you try to troll me (or just pretend, I don't know).


No, I am not trolling you.


Have you ever seen tables with commas left in there?


It's called CSV.


I've never seen in my whole life. And you should understand why.

Have you ever seen a website with sparse menu items or 'cloud' tags
with commas attached?
Have you ever heard someone claim that writing a 2d matrix down in a
single line is better that present it as a table?

So what you find _incredibly_ subjective here?


Neither of those examples is program code. You are asking for a
syntactic change to a *programming language*. Everything you've said
is fine for a non-code format. Nothing is applicable to a programming
language.


Why should this be a language feature? Why not just create a data file
and then load it, or use a triple quoted string and write your own
parser? What's the advantage of making this language syntax?


I am not sure what happens if I make another argument -
if it feels so easy for you to deny the obvious improvements (which
also supported by whole worlds' typography experience) then you can
just as easy deny pretty everything. How would we build any conversation
then?


Good question. You're clearly not interested in doing things the
existing (and easy) way, so there's no point debating this.
Fortunately for the rest of us, status quo wins a stalemate.

ChrisA



Please stop feeding the OP, to my knowledge he's never once come up with 
any sensible suggestion for Python.


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

Mark Lawrence

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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Chris Angelico
On Wed, May 9, 2018 at 7:15 AM, Mikhail V  wrote:
> On Tue, May 8, 2018 at 5:25 PM, Chris Angelico  wrote:
>> On Tue, May 8, 2018 at 10:52 PM, Mikhail V  wrote:
>>> Right? Your issues with tabs aside, I think it is impossible to ignore the
>>> the readability improvement. Not even speaking of how
>>> many commas and bracket you need to type in the first case.
>>
>> That's incredibly subjective. Or else straight-up wrong, I'm not sure which.
>
> Just admit it, you try to troll me (or just pretend, I don't know).

No, I am not trolling you.

> Have you ever seen tables with commas left in there?

It's called CSV.

> I've never seen in my whole life. And you should understand why.
>
> Have you ever seen a website with sparse menu items or 'cloud' tags
> with commas attached?
> Have you ever heard someone claim that writing a 2d matrix down in a
> single line is better that present it as a table?
>
> So what you find _incredibly_ subjective here?

Neither of those examples is program code. You are asking for a
syntactic change to a *programming language*. Everything you've said
is fine for a non-code format. Nothing is applicable to a programming
language.

>> Why should this be a language feature? Why not just create a data file
>> and then load it, or use a triple quoted string and write your own
>> parser? What's the advantage of making this language syntax?
>
> I am not sure what happens if I make another argument -
> if it feels so easy for you to deny the obvious improvements (which
> also supported by whole worlds' typography experience) then you can
> just as easy deny pretty everything. How would we build any conversation
> then?

Good question. You're clearly not interested in doing things the
existing (and easy) way, so there's no point debating this.
Fortunately for the rest of us, status quo wins a stalemate.

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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Mikhail V
On Tue, May 8, 2018 at 5:25 PM, Chris Angelico  wrote:
> On Tue, May 8, 2018 at 10:52 PM, Mikhail V  wrote:
>> Right? Your issues with tabs aside, I think it is impossible to ignore the
>> the readability improvement. Not even speaking of how
>> many commas and bracket you need to type in the first case.
>
> That's incredibly subjective. Or else straight-up wrong, I'm not sure which.

Just admit it, you try to troll me (or just pretend, I don't know).

Have you ever seen tables with commas left in there?
I've never seen in my whole life. And you should understand why.

Have you ever seen a website with sparse menu items or 'cloud' tags
with commas attached?
Have you ever heard someone claim that writing a 2d matrix down in a
single line is better that present it as a table?

So what you find _incredibly_ subjective here?

I am not telling tabulations work as they should in many code editors, but
there is a lot of work people invest to make better support for them in editors.
Here is another indirect benefit of adding such syntax, as editor developers
will be more motivated to improve the tabulation features.


> Why should this be a language feature? Why not just create a data file
> and then load it, or use a triple quoted string and write your own
> parser? What's the advantage of making this language syntax?

I am not sure what happens if I make another argument -
if it feels so easy for you to deny the obvious improvements (which
also supported by whole worlds' typography experience) then you can
just as easy deny pretty everything. How would we build any conversation
then?




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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Chris Angelico
On Wed, May 9, 2018 at 6:16 AM, Mikhail V  wrote:
> Also I don't know what kind of human thinks that this:
>  a + b
>  is two elements "a" and "+ b"
> What is "+ b"?

Unary plus applied to whatever value 'b' is.

> And who writes "- b" with a space in unary minus?
> I don't. Nobody does. Is it allowed? yes. no problem.

You're making a syntax proposal. That means it has to cope with all
the vagaries of syntax, including things that you think "nobody does".

>> - the first one is unambiguous while the second is ambiguous;
>
> I think it's time to reveal what exactly you mean here.
> In the above example there is nothing ambigious.
> At least not for someone who is Ok with basic editing
> skills.

There are things that are ambiguous to the Python syntax parser.

If you want to create a completely new syntax that happens to
incorporate some Python expressions, that's not a problem. It isn't a
Python syntax enhancement, it is a completely separate file format,
and you can do what you like with that. You can use tabs to separate
tokens, eval() those tokens to figure out the actual value, and then
build the resulting data structure according to your rules. And it's
100% acceptable to demand a stricter form of Python syntax within your
tokens (eg "no tabs allowed"), because it's your own data file.

And, even better: You can write code to parse this, without needing
approval from the core devs. The code you write doesn't have to wait
until Python 3.8 is released (two years from now); it can run on
existing interpreters. All the advantages are on your side.

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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Mikhail V
On Tue, May 8, 2018 at 6:20 PM, Steven D'Aprano
 wrote:
> On Tue, 08 May 2018 15:52:12 +0300, Mikhail V wrote:
>
>>> Last time you brought up this idea, you were told that it is ambiguous.
>>> Using whitespace alone, it is impossible to distinguish between
>>>
>>> a + b
>>>
>>> and
>>>
>>> a + b
>>>
>>>
>>> Can you see the difference? Of course not. That's the whole point. It
>>> is ambiguous. The first is a single item consisting of a plus b, and
>>> the second is two items consisting of a, following by unary plus b.
>>
>> Can you be more precise what issue are you addressing?
>
> Was I not clear enough the first time?
>
> When you write "a + b" it is impossible for either the human reader or
> the interpreter to tell whether that is meant to be two items separated
> by white space ("a" and "+b") or a single item ("a+b").
>
> There is no acceptable work-around or fix for this.
>
> * It is not acceptable to prohibit whitespace between unary operators
>   and their operand;
>
> * or to require spaces rather than tabs between binary operators
>   and their operands;
>

Sorry this all does not seem to even refer to my proposal.

I don't propose to remove spaces, but I propose Tab-separated
elements. If I allow commas as well, this will become not so simple,
probably. Also I don't propose syntax for e-mail code exchange,
but rather syntax for *work* an this can potentially help a lot of people
in everyday work.

Also I don't know what kind of human thinks that this:
 a + b
 is two elements "a" and "+ b"
What is "+ b"? And who writes "- b" with a space in unary minus?
I don't. Nobody does. Is it allowed? yes. no problem.

(It would be great if you group the issues
related to usability separetely from technical problems
with parser. That will help to understand you comments.)


>> Last time and
>> this time I told it uses TAB character to separate elements.
>
> That's not my recollection. As I remember it, it was *your* idea to use
> tab characters, and everyone told you that was not an acceptable work-
> around.

Yes my idea, but not sure what is you concern right now.
IIRC back then, you were the *only one* who commented something about
Tab and parsing, and made some mysterious example with eval("\t") which
I still don't know what it should explain exactly.
You say "everyone?" ... Hmm, now I am starting to suspect - maybe
each your post really represents a result of a quick meeting
regarding each raised proposal?
That would explain the usage of plural "us".

>>> There's also the problem that your syntax requires the *invisible*
>>> difference between tabs and spaces to be treated as syntactically
>>> meaningful.

There is "invisible" difference in indentations tabs vs spaces - so what?
I don't want spaces or tabs visible - there is toggle "show tabs" and "toggle
show space" for that and many more usability features, as I already said.
Look, I work with layouts - there are: Indents, Tabs, spaces, En
space, Em space,
thin space, non-breaking space, "indent to here" control characters.
All those are useful parts of inner syntax - all are "invisible".
What point are you making after all?

Those are basically universal features. And thousands of Python people
already use tabs to align columns so you have to accept it - it is
part of many source code and tabulation formatting is a good and
useful feature, although not all editors cope good with that.


>>
>> What editor do you use? My editor can toggle tabs highlighting as
>> arrows, and I suppose almost any editor has good support for
>> highlighting of characters by search, etc. For NPP there are even
>> plugins like Regex helper.
>
> Using a particular editor is not and will not be a mandatory requirement
> for Python.

Using outdated tools or being PEBCAK are not and will not be justification for
language syntax improvements. Using an editor from 85 - everyone else
should bother?
As said there is already tons of code with which you may be unsatisfied
when you paste it into REPL, but nearly nobody uses REPL for work.

>
> [...]
>> So you would prefer this:
>>
>> L = (
>> (a, 1),
>> (b, 2),
>> (c, 3),
>> (foobar, 4))
>>
>> over this:
>>
>> L === T/T:
>> a1
>> b2
>> c3
>> foobar4
>>
>> Right?
>
> I am amused that you have obviously gone to a lot of trouble to carefully
> line up the columns, and yet they aren't even aligned -- "foobar" extends
> into the second column, pushing the "4" out to the right.

No, i haven't. It takes much less time to type that than bracketed
version. Though I am amused that you've noticed the misaligned
element but can't notice how bad the bracketed version look.
Ok, Steve, as said, I hear you - you like the ugly one, I'll pick the cute
one ;-)


> There is no doubt that the first is HUGELY better:
>
> - it uses the standard = assignment operator, not a
>   special "===" operator;
>
> - there's no cryptic and mysterious "T/T" code which looks like
>   you are dividing T by T;

Your 

Re: Module, Package

2018-05-08 Thread Sharan Basappa
On Tuesday, 8 May 2018 13:05:58 UTC+5:30, Steven D'Aprano  wrote:
> On Mon, 07 May 2018 09:53:45 -0700, Sharan Basappa wrote:
> 
> > I am a bit confused between module and package in Python. Does a module
> > contain package or vice versa? When we import something in Python, do we
> > import a module or a package?
> 
> The term "module" in Python has multiple meanings:
> 
> - a particular kind of object, types.ModuleType
> 
> - a single importable .py, .pyc etc file
> 
> A package is a logical collection of importable .py etc files, usually 
> collected inside a single directory. When you import a module of a 
> package, that gives you a module object.
> 
> Normally we would say that packages contain modules. For example, if you 
> have this file structure:
> 
> 
> library/
> +-- __init__.py   # special file which defines a package
> +-- widgets.py
> +-- stuff/
> +-- __init__.py
> +-- things.py
> 
> 
> then we have a package "library", which in turn contains a submodule 
> "library.widgets", and a subpackage "library.stuff", which in turn 
> contains a submodule "library.stuff.things".
> 
> Each of these lines imports a module object:
> 
> import library
> import library.stuff
> import library.stuff.things
> import library.widgets
> 
> from library import widgets
> from library.stuff import things
> 
> 
> Effectively, "packages" relates to how you arrange the files on disk; 
> "modules" relates to what happens when you import them.
> 
> 
> -- 
> Steve

Wow! Thanks a lot.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem in compiling C API in mingw

2018-05-08 Thread m.overmeyer--- via Python-list
On Tuesday, 26 July 2011 23:53:36 UTC, llw...@gmail.com  wrote:
> Hi all again, 
>   I wonder if so far only Python 2.5.x support c extension. I try the
> MSVC 2010 and 2008, also try mingw (gcc 4.x.x) and swig. But even I try
> the simplest example, it said 
> 
> example_wrap.o:example_wrap.c:(.text+0x10ac): undefined reference to 
> `_imp__PyObject_Free'
> example_wrap.o:example_wrap.c:(.text+0x10f5): undefined reference to 
> `_imp__PyCapsule_Import'
> example_wrap.o:example_wrap.c:(.text+0x1100): undefined reference to 
> `_imp__PyErr_Occurred'
> example_wrap.o:example_wrap.c:(.text+0x110e): undefined reference to 
> `_imp__PyErr_Clear'
> example_wrap.o:example_wrap.c:(.text+0x1125): undefined reference to 
> `_imp__PyImport_AddModule'
> example_wrap.o:example_wrap.c:(.text+0x1144): undefined reference to 
> `_imp__PyCapsule_New'
> example_wrap.o:example_wrap.c:(.text+0x1165): undefined reference to 
> `_imp__PyModule_AddObject'
> example_wrap.o:example_wrap.c:(.text+0x1170): undefined reference to 
> `_imp__PyBaseObject_Type'
> example_wrap.o:example_wrap.c:(.text+0x11b2): undefined reference to 
> `_imp__PyObject_SetAttr'
> example_wrap.o:example_wrap.c:(.rdata+0x1e8): undefined reference to 
> `PyObject_GenericGetAttr'
> collect2: ld returned 1 exit status
> 
> and some sort like that.
> 
> So I try to use the compiler itself and get rid of all 3rd part tool,
> here is what I did
> 
> / source code
> #include "Python.h"
> 
> static  PyObject *
> ex_foo(PyObject *self, PyObject *args)
> {
> printf("Hello, world n " );
> Py_INCREF(Py_None);
> return  Py_None;
> }
> 
> static  PyMethodDef example_methods[] = {
> {"foo" , ex_foo, METH_VARARGS, "foo() doc string" },
> {NULL , NULL }
> };
> 
> static  struct  PyModuleDef examplemodule = {
> PyModuleDef_HEAD_INIT,
> "example" ,
> "example module doc string" ,
> -1 ,
> example_methods,
> NULL ,
> NULL ,
> NULL ,
> NULL
> };
> 
> PyMODINIT_FUNC
> PyInit_example(void )
> {
> return  PyModule_Create(&examplemodule);
> }
> 
> /// my setup.py
> from distutils.core import setup, Extension
> 
> module1 = Extension('example', sources = ['example.c'])
> 
> setup (name = 'example', version = '1.0', description = 'This is a demo 
> package', ext_modules = [module1])
> 
> 
> // running
> python setup.py build --compiler=mingw32
> 
> 
> $ python setup.py build --compiler=mingw32
> running build
> running build_ext
> building 'example' extension
> D:\Programs\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall "-Ic:\Program Files 
> (x8
> 6)\Python\include" "-Ic:\Program Files (x86)\Python\PC" -c example.c -o 
> build\te
> mp.win-amd64-3.1\Release\example.o
> writing build\temp.win-amd64-3.1\Release\example.def
> D:\Programs\MinGW\bin\gcc.exe -mno-cygwin -shared -s 
> build\temp.win-amd64-3.1\Re
> lease\example.o build\temp.win-amd64-3.1\Release\example.def "-Lc:\Program 
> Files
>  (x86)\Python\libs" "-Lc:\Program Files (x86)\Python\PCbuild\amd64" 
> -lpython31 -
> lmsvcr90 -o build\lib.win-amd64-3.1\example.pyd
> build\temp.win-amd64-3.1\Release\example.o:example.c:(.text+0x13): undefined 
> ref
> erence to `_imp___Py_NoneStruct'
> build\temp.win-amd64-3.1\Release\example.o:example.c:(.text+0x32): undefined 
> ref
> erence to `_imp__PyModule_Create2'
> collect2: ld returned 1 exit status
> error: command 'gcc' failed with exit status 1
> - Original Message Ends 

You are linking against the static version of the Python library. If you link 
against the DLL version, this problem goes away.

-Lc:\Program Files(x86)\Python\libs" should just be "-Lc:\Program 
Files(x86)\Python\", assuming that's where the Python DLLs are.

See:
https://stackoverflow.com/questions/5159353/how-can-i-get-rid-of-the-imp-prefix-in-the-linker-in-vc#5159395

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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Steven D'Aprano
On Tue, 08 May 2018 15:52:12 +0300, Mikhail V wrote:

>> Last time you brought up this idea, you were told that it is ambiguous.
>> Using whitespace alone, it is impossible to distinguish between
>>
>> a + b
>>
>> and
>>
>> a + b
>>
>>
>> Can you see the difference? Of course not. That's the whole point. It
>> is ambiguous. The first is a single item consisting of a plus b, and
>> the second is two items consisting of a, following by unary plus b.
> 
> Can you be more precise what issue are you addressing?

Was I not clear enough the first time?

When you write "a + b" it is impossible for either the human reader or 
the interpreter to tell whether that is meant to be two items separated 
by white space ("a" and "+b") or a single item ("a+b").

The same applies to "a - b".

There is no acceptable work-around or fix for this.

* It is not acceptable to prohibit whitespace between unary operators
  and their operand;

* or to require spaces rather than tabs between binary operators
  and their operands;

* or to make a subtle semantic difference between tabs and spaces
  of this sort.

Unix "make" files require tabs rather than spaces, and it is a constant 
source of bugs and frustration.


> Last time and
> this time I told it uses TAB character to separate elements.

That's not my recollection. As I remember it, it was *your* idea to use 
tab characters, and everyone told you that was not an acceptable work-
around.

Who told you to use tab characters? It would not have been any of the 
core developers. Many of them would rather ban tabs than require them.


>> There's also the problem that your syntax requires the *invisible*
>> difference between tabs and spaces to be treated as syntactically
>> meaningful.
> 
> What editor do you use? My editor can toggle tabs highlighting as
> arrows, and I suppose almost any editor has good support for
> highlighting of characters by search, etc. For NPP there are even
> plugins like Regex helper.

Using a particular editor is not and will not be a mandatory requirement 
for Python.


[...]
> So you would prefer this:
> 
> L = (
> (a, 1),
> (b, 2),
> (c, 3),
> (foobar, 4))
> 
> over this:
> 
> L === T/T:
> a1
> b2
> c3
> foobar4
> 
> Right?

I am amused that you have obviously gone to a lot of trouble to carefully 
line up the columns, and yet they aren't even aligned -- "foobar" extends 
into the second column, pushing the "4" out to the right.

There is no doubt that the first is HUGELY better:

- it uses the standard = assignment operator, not a 
  special "===" operator;

- there's no cryptic and mysterious "T/T" code which looks like
  you are dividing T by T;

- the first one allows you to write it as a single line:

L = ((a, 1), (b, 2), (c, 3), (foobar, 4))

  instead of wasting vertical space;

- the first one is unambiguous while the second is ambiguous;

- the first one can include nested data structures, while 
  the second cannot.

There is only one advantage to the second format. It gives bad 
programmers a justification to waste time while pretending to be working, 
as they carefully align their columns, then realign them each time the 
data changes.


> Your issues with tabs aside, I think it is impossible to ignore
> the the readability improvement.

An interesting philosophical conundrum... is it possible to ignore 
something which isn't there?

If there is no elephant in the room, and nobody mentions it, are they 
ignoring it?



-- 
Steve

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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Liste guru

Il 08/05/2018 14:52, Mikhail V ha scritto:

 ...

What editor do you use? My editor can toggle tabs highlighting as arrows,
and I suppose almost any editor has good support for highlighting of
characters by search, etc. For NPP there are even plugins like Regex helper.


    I like to 'type program.py' and understand what's happening, 
without have to fire up an editor.


   While, in C++, the Microsoft IDE (and some other) mark the class 
members & the parameters so you can easily see what 'counter' is, a lot 
of guide says that you should call it 'm_counter' if it's a member or 
'counter_' if it's a parameter, just in case you don't have your editor 
(or you're colorblind or you don't like to have the parameters printed 
with a light grey ...).



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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Chris Angelico
On Tue, May 8, 2018 at 10:52 PM, Mikhail V  wrote:
> Right? Your issues with tabs aside, I think it is impossible to ignore the
> the readability improvement. Not even speaking of how
> many commas and bracket you need to type in the first case.

That's incredibly subjective. Or else straight-up wrong, I'm not sure which.

Why should this be a language feature? Why not just create a data file
and then load it, or use a triple quoted string and write your own
parser? What's the advantage of making this language syntax?

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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Mikhail V
On Tue, May 8, 2018 at 10:15 AM, Steven D'Aprano
 wrote:
> On Tue, 08 May 2018 06:45:05 +0300, Mikhail V wrote:
>
>> *Example 3. Two-dimensional tuple.*
>>
>> data === T/T :
>> 123"hello"
>> ab c + de f
>>
>> is a synonym for:
>>
>> data = (
>> (1, 2, 3, "hello") ,
>> (a, b, c + d, e, f ) )
>
> Last time you brought up this idea, you were told that it is ambiguous.
> Using whitespace alone, it is impossible to distinguish between
>
> a + b
>
> and
>
> a + b
>
>
> Can you see the difference? Of course not. That's the whole point. It is
> ambiguous. The first is a single item consisting of a plus b, and the
> second is two items consisting of a, following by unary plus b.

Can you be more precise what issue are you addressing?
Last time and this time I told it uses TAB character to
separate elements.


> There's also the problem that your syntax requires the *invisible*
> difference between tabs and spaces to be treated as syntactically
> meaningful.

What editor do you use? My editor can toggle tabs highlighting as arrows,
and I suppose almost any editor has good support for highlighting of
characters by search, etc. For NPP there are even plugins like Regex helper.

The only real issue I know that there may be no option to adjust the
minimal size for a tabulation, so it can become too small
in some rare cases, and there is the highlight function for that.

I never had problems with inputing tables - It seems you are having
an issue or may be it's even some personal pet-pieve.

>
> [...]
>> *The benefits is just as in above examples : readability and
>> 'typeability' boost.*
>
> But your syntax is not more readable, it is less readable and ambiguous.
> It requires us to care about the difference between two kinds of
> invisible whitespace.

Yes it requires you to care about tabulation - which many users already do
to improve readability in their code. As well as any software like
Matlab, Excel, etc presents matrices as tables.
So they are all making it "less readable", lol.
Ok Steven, you like the brackets and commas noise, that's
quite funny. Your opinion is heard, but I would be thankful if you'll
speak for yourself,
and not try to enforce your opinion with these "us", "for us".

Also you seem to start with cherry-picking straight away - trying
to find an issue and wind it up with the whole idea, totally ignoring
obvious benefits for most frequent use cases like multiline
strings,1d tuples/lists  and simple tables.
A very common table case is a 2-column table.

So you would prefer this:

L = (
(a, 1),
(b, 2),
(c, 3),
(foobar, 4))

over this:

L === T/T:
a1
b2
c3
foobar4

Right? Your issues with tabs aside, I think it is impossible to ignore the
the readability improvement. Not even speaking of how
many commas and bracket you need to type in the first case.


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


Re: Problem/bug with class definition inside function definition

2018-05-08 Thread Ned Batchelder

On 5/8/18 3:55 AM, Alexey Muranov wrote:
Sorry, i was confused.  I would say that this mostly works as 
expected, though the difference between


   x = 42

   class C:
   x = x  # Works

and

   def f2(a):
   class D:
   a = a  # Does not work <
   return D

is still surprising to me.

Otherwise, probably the solution with

   def f(a):
   _a = a
   class D:
   a = _a
   return D

is good enough, if Python does not allow to refer "simultaneously" to 
variables from different scopes if they have the same name.


Alexey.


I'm curious to see the real code you're writing that uses this style of 
class creation.  It feels like there might be an easier way to achieve 
your goal.


--Ned.



On Tue, 8 May, 2018 at 12:21 AM, Alexey Muranov 
 wrote:

To be more exact, i do see a few workarounds, for example:


   def f4(a):
   b = a
   class D:
   a = b  # Works
   return D

But this is not what i was hoping for.

Alexey.

On Tue, 8 May, 2018 at 12:02 AM, Alexey Muranov 
 wrote:
I have discovered the following bug or problem: it looks like i am 
forced to choose different names for class attributes and function 
arguments, and i see no workaround.  Am i missing some special 
syntax feature ?


Alexey.

---
x = 42

class C1:
   y = x  # Works

class C2:
   x = x  # Works

# ---
def f1(a):
   class D:
   b = a  # Works
   return D

def f2(a):
   class D:
   a = a  # Does not work <
   return D

def f3(a):
   class D:
   nonlocal a
   a = a  # Does not work either <
   return D

# ---
def g1(a):
   def h():
   b = a  # Works
   return b
   return h

def g2(a):
   def h():
   a = a  # Does not work (as expected)
   return a
   return h

def g3(a):
   def h():
   nonlocal a
   a = a  # Works
   return a
   return h

# ---
if __name__ == "__main__":
   assert C1.y == 42
   assert C2.x == 42

   assert f1(13).b == 13

   try:
   f2(13)  # NameError
   except NameError:
   pass
   except Exception as e:
   raise Exception( 'Unexpected exception raised: '
    '{}'.format(type(e).__name__) )
   else:
   raise Exception('No exception')

   try:
   f3(13).a  # AttributeError
   except AttributeError:
   pass
   except Exception as e:
   raise Exception( 'Unexpected exception raised: '
    '{}'.format(type(e).__name__) )
   else:
   raise Exception('No exception')

   assert g1(13)() == 13

   try:
   g2(13)()  # UnboundLocalError
   except UnboundLocalError:
   pass
   except Exception as e:
   raise Exception( 'Unexpected exception raised: '
    '{}'.format(type(e).__name__) )
   else:
   raise Exception('No exception')

   assert g3(13)() == 13







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


Re: itemgetter with default arguments

2018-05-08 Thread Antoon Pardon
On 07-05-18 17:45, Peter Otten wrote:
> Antoon Pardon wrote:
>
>> On 05-05-18 09:33, Peter Otten wrote:
>>> I think you have established that there is no straight-forward way to
>>> write this as a lambda. But is adding a default to itemgetter the right
>>> conclusion?
>>>
>>> If there were an exception-catching decorator you could write
>>>
>>> f = catch(IndexError, "spam")(itemgetter(2))
>> I think your catch function would be a usefull addition, but I don't see
>> it solving this problem once we use itemgetter te get multiple entries.
> Good catch()
>
> ;)
>
> The obvious way, expressing the n-tuple case in terms of the solution for 
> scalars
>
 f = lambda items: tuple(catch(IndexError, "spam")(itemgetter(i))(items) 
> for i in (2, 1, 5))
>>> f("abc")
> ('c', 'b', 'spam')
>
> is a bit too complex to inline -- and also inefficient. You'd be tempted to 
> factor out the repetetive parts
>
 f = lambda items, gets=[catch(IndexError, "spam")(itemgetter(i)) for i 
> in (2, 1, 5)]: tuple(get(items) for get in gets)
 f("abc")
> ('c', 'b', 'spam')
>
> and thus make it even less readable.
>
> That said -- grepping my code I'm a bit surprised to find only
>
> 17 itemgetter(0)
>  9 itemgetter(1)
>  1 itemgetter(1, 0)
>  1 itemgetter(*indices)
>
> Checking /usr/lib/python3/dist-packages it looks like the situation is 
> similar. I conclude that the most useful addition to the operator module 
> would be
>
> first = itemgetter(0)
> second = itemgetter(1)

The problem with looking for such uses, is that I am working on a lot of
legacy code written in 2.2. It needed few adaptions to still work in 2.7
but I didn't adapt the code to make use of all the new features. But looking
at sort statements, it seems I have (the equivallent of) the following

itemgetter(2)
itemgetter(3)
itemgetter(4)
itemgetter(slice(0,-1))

-- 
Antoon Pardon.

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


Re: Problem/bug with class definition inside function definition

2018-05-08 Thread Alexey Muranov
Sorry, i was confused.  I would say that this mostly works as expected, 
though the difference between


   x = 42

   class C:
   x = x  # Works

and

   def f2(a):
   class D:
   a = a  # Does not work <
   return D

is still surprising to me.

Otherwise, probably the solution with

   def f(a):
   _a = a
   class D:
   a = _a
   return D

is good enough, if Python does not allow to refer "simultaneously" to 
variables from different scopes if they have the same name.


Alexey.


On Tue, 8 May, 2018 at 12:21 AM, Alexey Muranov 
 wrote:

To be more exact, i do see a few workarounds, for example:


   def f4(a):
   b = a
   class D:
   a = b  # Works
   return D

But this is not what i was hoping for.

Alexey.

On Tue, 8 May, 2018 at 12:02 AM, Alexey Muranov 
 wrote:
I have discovered the following bug or problem: it looks like i am 
forced to choose different names for class attributes and function 
arguments, and i see no workaround.  Am i missing some special 
syntax feature ?


Alexey.

---
x = 42

class C1:
   y = x  # Works

class C2:
   x = x  # Works

# ---
def f1(a):
   class D:
   b = a  # Works
   return D

def f2(a):
   class D:
   a = a  # Does not work <
   return D

def f3(a):
   class D:
   nonlocal a
   a = a  # Does not work either <
   return D

# ---
def g1(a):
   def h():
   b = a  # Works
   return b
   return h

def g2(a):
   def h():
   a = a  # Does not work (as expected)
   return a
   return h

def g3(a):
   def h():
   nonlocal a
   a = a  # Works
   return a
   return h

# ---
if __name__ == "__main__":
   assert C1.y == 42
   assert C2.x == 42

   assert f1(13).b == 13

   try:
   f2(13)  # NameError
   except NameError:
   pass
   except Exception as e:
   raise Exception( 'Unexpected exception raised: '
'{}'.format(type(e).__name__) )
   else:
   raise Exception('No exception')

   try:
   f3(13).a  # AttributeError
   except AttributeError:
   pass
   except Exception as e:
   raise Exception( 'Unexpected exception raised: '
'{}'.format(type(e).__name__) )
   else:
   raise Exception('No exception')

   assert g1(13)() == 13

   try:
   g2(13)()  # UnboundLocalError
   except UnboundLocalError:
   pass
   except Exception as e:
   raise Exception( 'Unexpected exception raised: '
'{}'.format(type(e).__name__) )
   else:
   raise Exception('No exception')

   assert g3(13)() == 13





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


Re: Module, Package

2018-05-08 Thread Steven D'Aprano
On Mon, 07 May 2018 09:53:45 -0700, Sharan Basappa wrote:

> I am a bit confused between module and package in Python. Does a module
> contain package or vice versa? When we import something in Python, do we
> import a module or a package?

The term "module" in Python has multiple meanings:

- a particular kind of object, types.ModuleType

- a single importable .py, .pyc etc file

A package is a logical collection of importable .py etc files, usually 
collected inside a single directory. When you import a module of a 
package, that gives you a module object.

Normally we would say that packages contain modules. For example, if you 
have this file structure:


library/
+-- __init__.py   # special file which defines a package
+-- widgets.py
+-- stuff/
+-- __init__.py
+-- things.py


then we have a package "library", which in turn contains a submodule 
"library.widgets", and a subpackage "library.stuff", which in turn 
contains a submodule "library.stuff.things".

Each of these lines imports a module object:

import library
import library.stuff
import library.stuff.things
import library.widgets

from library import widgets
from library.stuff import things


Effectively, "packages" relates to how you arrange the files on disk; 
"modules" relates to what happens when you import them.


-- 
Steve

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


Re: Suggestion for a "data" object syntax

2018-05-08 Thread Steven D'Aprano
On Tue, 08 May 2018 06:45:05 +0300, Mikhail V wrote:

> *Example 3. Two-dimensional tuple.*
> 
> data === T/T :
> 123"hello"
> ab c + de f
> 
> is a synonym for:
> 
> data = (
> (1, 2, 3, "hello") ,
> (a, b, c + d, e, f ) )

Last time you brought up this idea, you were told that it is ambiguous. 
Using whitespace alone, it is impossible to distinguish between

a + b

and 

a + b


Can you see the difference? Of course not. That's the whole point. It is 
ambiguous. The first is a single item consisting of a plus b, and the 
second is two items consisting of a, following by unary plus b.

The same applies to unary minus.

That problem *alone* kills this idea.

There's also the problem that your syntax requires the *invisible* 
difference between tabs and spaces to be treated as syntactically 
meaningful.

[...]
> *The benefits is just as in above examples : readability and
> 'typeability' boost.*

But your syntax is not more readable, it is less readable and ambiguous. 
It requires us to care about the difference between two kinds of 
invisible whitespace.


> To present nesting of elements of higher than 2 levels, normal Python
> syntax can be used for deeper nesting:

So not only does idea not give us any new benefit, it cannot even do what 
existing syntax can do. It is inferior to what Python already has, 
ambiguous, and hard to read.

-- 
Steve

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