Re: frozendict: an experiment

2020-07-21 Thread Marco Sulla
On Tue, 21 Jul 2020 at 06:01, Inada Naoki  wrote:

> On Tue, Jul 21, 2020 at 5:07 AM Marco Sulla  wrote:
> >
> > I just finished to improve the performance of frozendict creation. The
> result is very promising.
> >
> > The speedup is about 30% for small dicts (8 items). For large dicts (1k
> items) is about 38% for dicts with only integers as keys and values, and
> 45% for dicts with only strings.
>
> Do you mean `frozendict(d)` where d is frozendict?
>

No, I mean a dictionary.
-- 
https://mail.python.org/mailman/listinfo/python-list


EuroPython 2020: Presenting our Conference Booklet

2020-07-21 Thread M.-A. Lemburg
Our designer Jessica has created a beautiful conference booklet for
you to use during the conference and keep as a memory afterwards. It
provides all details, schedule, keynotes, sponsor listings, etc. in a
single PDF.

* EuroPython 2020 Conference Booklet *

   https://ep2020.europython.eu/events/conference-booklet/

We'd normally give out the booklet as part of the conference bag, but
since we’re running the event online, we’ve put up the PDF of the
booklet instead for your to enjoy.

If you feel like there something in our program which you may benefit
from or you just want to get a feeling for what a EuroPython
conference is like, please consider joining the event.

Tickets still available
---

Even though we have surpassed the 900 tickets mark already, we still
have tickets available, both in form of the paid conference & sprint
tickets as well as the free sprints-only tickets.

Please head over to our registration page to book your tickets:

https://ep2020.europython.eu/registration/buy-tickets/



Help spread the word


Please help us spread this message by sharing it on your social
networks as widely as possible. Thank you !

Link to the blog post:

https://blog.europython.eu/post/624240002899066880/europython-2020-presenting-our-conference-booklet

Tweet:

https://twitter.com/europython/status/1285498603360923656

Thanks,
--
EuroPython 2020 Team
https://ep2020.europython.eu/
https://www.europython-society.org/

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


Python Program Help

2020-07-21 Thread ksikor14--- via Python-list
I can't seem to figure out what I am doing wrong.  I have tried everything.  
This is what it is supposed to do:

(1) Prompt the user for a title for data. Output the title. (1 pt)

Ex:

Enter a title for the data:
Number of Novels Authored
You entered: Number of Novels Authored

(2) Prompt the user for the headers of two columns of a table. Output the 
column headers. (1 pt)

Ex:

Enter the column 1 header:
Author name
You entered: Author name

Enter the column 2 header:
Number of novels
You entered: Number of novels

(3) Prompt the user for data points. Data points must be in this format: 
string, int. Store the information before the comma into a string variable and 
the information after the comma into an integer. The user will enter -1 when 
they have finished entering data points. Output the data points. Store the 
string components of the data points in a list of strings. Store the integer 
components of the data points in a list of integers. (4 pts)

Ex:

Enter a data point (-1 to stop input):
Jane Austen, 6
Data string: Jane Austen
Data integer: 6

(4) Perform error checking for the data point entries. If any of the following 
errors occurs, output the appropriate error message and prompt again for a 
valid data point.

If entry has no comma
Output: Error: No comma in string. (1 pt)
If entry has more than one comma
Output: Error: Too many commas in input. (1 pt)
If entry after the comma is not an integer
Output: Error: Comma not followed by an integer. (2 pts)

Ex:

Enter a data point (-1 to stop input):
Ernest Hemingway 9
Error: No comma in string.

Enter a data point (-1 to stop input):
Ernest, Hemingway, 9
Error: Too many commas in input.

Enter a data point (-1 to stop input):
Ernest Hemingway, nine
Error: Comma not followed by an integer.

Enter a data point (-1 to stop input):
Ernest Hemingway, 9
Data string: Ernest Hemingway
Data integer: 9

(5) Output the information in a formatted table. The title is right justified 
with a minimum field width value of 33. Column 1 has a minimum field width 
value of 20. Column 2 has a minimum field width value of 23. (3 pts)

Ex:

Number of Novels Authored
Author name |   Number of novels

Jane Austen |  6
Charles Dickens | 20
Ernest Hemingway|  9
Jack Kerouac| 22
F. Scott Fitzgerald |  8
Mary Shelley|  7
Charlotte Bronte|  5
Mark Twain  | 11
Agatha Christie | 73
Ian Flemming| 14
J.K. Rowling| 14
Stephen King| 54
Oscar Wilde |  1

(6) Output the information as a formatted histogram. Each name is right 
justified with a minimum field width value of 20. (4 pts)

Ex:

 Jane Austen **
 Charles Dickens 
Ernest Hemingway *
Jack Kerouac **
 F. Scott Fitzgerald 
Mary Shelley ***
Charlotte Bronte *
  Mark Twain ***
 Agatha Christie 
*
Ian Flemming **
J.K. Rowling **
Stephen King **
 Oscar Wilde *

Here is my code:

data_title = input("Enter a title for the data:\n")
print("You entered:", data_title)
h1 = input("\nEnter the column 1 header:\n")
print("You entered:", h1)
h2 = input("\nEnter the column 2 header:\n")
print("You entered:", h2)
point = input("\nEnter a data point (-1 to stop input):\n")

data = []
while point != "-1":
words = point.split(",")
if len(words) == 1:
print("Error: No comma in string.")
elif len(words) > 2:
print("Error: Too many commas in input. ")
else:
try:
author = words[0]
num_novels = int(words[1])
print("Author:", author)
print("Number of Novel(s):", num_novels)
data.append((author, num_novels))
except ValueError:
print("Error: Comma not followed by an integer.")
point = input("\nEnter a data point (-1 to stop input):\n")

print("%33s" % data_title)
print("%-20s|%23s" % (h1, h2))
print("-" * 44)
for item in data:
print("%-20s|%23d" % (item[0], item[1]))
for item in data:
print("%20s %s" % (item[0], '*' * item[1]))

I get this error:

Traceback (most recent call last):
  File "main.py", line 1, in 
data_title = input("Enter a title for the data:\n")
EOFError: EOF when reading a line

And can't seem to figure out how to correct it any help would be greatly 
appreciated.

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


Re: Python Program Help

2020-07-21 Thread MRAB

On 2020-07-21 14:38, ksikor14--- via Python-list wrote:

I can't seem to figure out what I am doing wrong.  I have tried everything.  
This is what it is supposed to do:

(1) Prompt the user for a title for data. Output the title. (1 pt)

Ex:

Enter a title for the data:
Number of Novels Authored
You entered: Number of Novels Authored


[snip]


Here is my code:

data_title = input("Enter a title for the data:\n")
print("You entered:", data_title)
h1 = input("\nEnter the column 1 header:\n")
print("You entered:", h1)
h2 = input("\nEnter the column 2 header:\n")
print("You entered:", h2)
point = input("\nEnter a data point (-1 to stop input):\n")

data = []
while point != "-1":
 words = point.split(",")
 if len(words) == 1:
 print("Error: No comma in string.")
 elif len(words) > 2:
 print("Error: Too many commas in input. ")
 else:
 try:
 author = words[0]
 num_novels = int(words[1])
 print("Author:", author)
 print("Number of Novel(s):", num_novels)
 data.append((author, num_novels))
 except ValueError:
 print("Error: Comma not followed by an integer.")
 point = input("\nEnter a data point (-1 to stop input):\n")

print("%33s" % data_title)
print("%-20s|%23s" % (h1, h2))
print("-" * 44)
for item in data:
 print("%-20s|%23d" % (item[0], item[1]))
for item in data:
 print("%20s %s" % (item[0], '*' * item[1]))

I get this error:

Traceback (most recent call last):
   File "main.py", line 1, in 
 data_title = input("Enter a title for the data:\n")
EOFError: EOF when reading a line

And can't seem to figure out how to correct it any help would be greatly 
appreciated.


How are you running it? At a system prompt with:

py main.py

or similar?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Friday Finking: Limiting parameters

2020-07-21 Thread Peter J. Holzer
On 2020-07-12 08:56:47 +1200, DL Neil via Python-list wrote:
> On 12/07/20 8:13 AM, Peter J. Holzer wrote:
> > On 2020-07-11 09:54:33 +1200, dn via Python-list wrote:
> > > Questions:
> > > 
> > > Is the idea of limiting the number of parameters passed across an 
> > > interface
> > > a real concern or somewhat an affectation?
> > > 
> > > Is three, five, seven, ... a valid limit (or warning-signal)?
> > > 
> > > Do you have a personal or corporate style or 'standard' to limit parameter
> > > lists to seven parameters, or some other number?
> > > 
> > > Given that Python enables labeled arguments ("keyword arguments"), does 
> > > the
> > > concern really only apply to 'us' in terms of numbers of "positional
> > > arguments"?
> > 
> > Keyword arguments greatly ameliorate the problems I have with long
> > parameter lists. While I think that calling a function with 7 positional
> > parameters is pretty much unreadable, with 7 named parameters (or maybe
> > 2 positional and 5 named parameters) it doesn't bother me much. The
> > definition of the function might have even more parameters, as long as
> > most of them are optional and have sensible defaults (subprocess.Popen
> > with 20 parameters (if I counted correctly) is pushing it, though).
> 
> Do you think, then, that the maxima should be applied to the number of
> arguments that will appear in the 'expected usage' of the routine? (cf the
> def's parameter-list) After all, calling Popen would rarely require all-20
> arguments be stated, given the acceptability of the defaults and the
> irrelevance of many 'special cases'.

Yes, pretty much. For typical usage, only a few parameters are needed,
and therefore those are the only ones a programmer has to remember. For
the others ... 
When reading code which uses an unfamiliar named parameter, looking it
up is straightforward, so no big deal.
When writing code, the programmer has to remember (or at least suspect)
that the function can do something to be able to look it up - so with a
large number of parameters there is a certain risk that the doesn't even
think of checking the docs. So a function with a large number of rarely
used parameters is still harder to use correctly than one with fewer
parameters, but not much.


> Alternately/additionally, do you feel that the power and readability of
> Python's keyword-arguments + default-values, requires a modification of the
> advice to only limit the number of positional-arguments?

Depends on the advice :-). But yes, I think the advice for a language
which supports named parameters should be different than than for a
language which doesn't. 


> Another discussion-point (which may be difficult because 'the answer' may
> vary according to implementation-requirements): rather than one do-it-all
> 'Swiss Army Knife' of a routine with dozens of parameters, might it be
> better-practice to code a number of methods/functions to take care of the
> special-cases, with a single 'core function' to carry-out the basic
> operations-required? (in a class environment: sub-classes maybe)

I think this depends a lot on the situation. If you have clearly
distinguished scenarios where you would have to use a specific set of
parameters, a set of functions (or methods, or subclasses) may help to
provide "the obvious way to do it". If that's not so clear or if that
would prevent some (legitimate) use-cases, the swiss army knife is
probably better.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | [email protected] |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Friday Finking: Limiting parameters

2020-07-21 Thread Peter J. Holzer
On 2020-07-13 17:21:40 +1200, dn via Python-list wrote:
> On 12/07/20 10:10 PM, Barry Scott wrote:
> > I'd expect to see something like this:
> > 
> > def mail_label( person, address ):
> > first_name = person.first_name
> > # or if you want a function interface
> > first_line_of_address = address.get_first_line()
> 
> Does this idea move whole objects across the interface? (see earlier in the
> thread)

Assigning an object in Python only copies a pointer (and may adjust some
house-keeping info, like a reference count). So it doesn't matter
whether the object  has 5 fields or 50. The function will only access
those it knows about and ignore the rest.

One might argue that mail_label should be a method of the person object
because it depends on the person (e.g., depending on the ethnicity of
the person the name might be written "first_name last_name" or
"last_name firstname"). OTOH a person may have many addresses (and an
address shared by many people), so a function which combines a person
and address (which therefore can't be a method of either person or
address) may be better. 

Maybe that should be treated as a model-view relationship: You have two
models (person and address) and a view (which combines some aspects of
both while ignoring others).

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | [email protected] |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Iterators, iterables and special objects

2020-07-21 Thread Peter Slížik
Hi list, two related questions:

1. Why do functions used to iterate over collections or dict members return
specialized objects like

type(dict.keys()) -> class 'dict_keys'
type(dict.values()) -> class 'dict_values'
type(dict.items()) -> class 'dict_items'
type(filter(..., ...)) -> class 'filter'
type(map(..., ...)) -> class 'map'
type(enumerate(...)) -> class 'enumerate'

instead of returning some more general 'iterable' and 'view' objects? Are
those returned objects really that different from one another that it makes
sense to have individual implementations?

2. Why do these functions return iterators instead of iterables? First, I
find it confusing - to me, it is the loop's job to create an iterator from
the supplied iterable, and not the object that is being iterated over. And
second, with this design, iterators are required to be iterables too, which
is confusing as hell (at least for people coming from other languages in
which the distinction is strict).

Thanks,
Peter
-- 
https://mail.python.org/mailman/listinfo/python-list


Python Scripts

2020-07-21 Thread Wasdeq68
im having problems when running python scripts

When running the scripts it always closes immediately
-- 
https://mail.python.org/mailman/listinfo/python-list


Upgrade from Python 3.6 to 3.8 and cx-freeze is not available more

2020-07-21 Thread Christian SCHEIBER / KLS GmbH
 

I’d like to do exe files, so the pythin interpreter has not tob e installed.

That’s why I use cx-freeze, but installing Python 3.8 after using Python 3.6
does not work.

 

Can you tell me how I can make cx-freeze in Python 3.8 or how I can produce
exe files for Windows 7 32 / 64 Bit and Win10?

Thanx in advance

 

 

Mit freundlichen Grüßen

 

Christian Scheiber

 

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


RE: Python Scripts

2020-07-21 Thread David Raymond
> im having problems when running python scripts
> 
> When running the scripts it always closes immediately

If you're running it in Windows, and running it by double clicking on a .py 
file, then it will pop up a console window while it's running, and then 
immediately close that window when the script is complete. So if the script is 
failing immediately or even succeeding quickly, then the window with all the 
output is closing immediately too.

If this is what's going on with you, you can open the console first and run the 
scripts from there. That way all their output will still be there for you to 
see when it's complete.

Alternatively as a temporary debugging solution you could surround the main 
part (or all) of the script in a try statement and in the except clause have a 
"hit enter to continue" bit to freeze it before it closes the window.


import traceback
try:
stuff
except:
traceback.print_exc()
raise
finally:
input("Hit Enter to close")

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


Re: Python Program Help

2020-07-21 Thread Terry Reedy

On 7/21/2020 11:08 AM, MRAB wrote:

On 2020-07-21 14:38, ksikor14--- via Python-list wrote:
I can't seem to figure out what I am doing wrong.  I have tried 
everything.  This is what it is supposed to do:

[snip]

I get this error:

Traceback (most recent call last):
   File "main.py", line 1, in 
 data_title = input("Enter a title for the data:\n")
EOFError: EOF when reading a line


The only way I discovered to get that error, on Windows, is to hit 
control-D in response to the prompt.  This is not a bug in your program, 
but part of standard interactive program on *nix, copied by Python on 
Windows also.  If the user who hits ^D does not mean to stop the 
program, then it is a user bug.


And can't seem to figure out how to correct it any help would be 
greatly appreciated.



How are you running it? At a system prompt with:

py main.py

or similar?


And what OS and what response did you make as the 'user'?


--
Terry Jan Reedy


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


RE: Python Scripts

2020-07-21 Thread David Raymond
Remember to reply-all, so that python-list is included and can still see 
responses and offer help.

If Python won't open them, then how do you know the scripts work? They work on 
someone else's computer you mean?

Please provide the basics then so we can try to help out.

What OS are you using?
How are you trying to start Python/run the scripts?
Are there any exceptions, error messages, etc when you try to run it?
Can you successfully run any other Python script, or is it just this one that's 
a problem?
What is in the script? (can be a summary to start with if the script is long)
What version of Python are you using?
Etc...


> no the scripts work but python wont open them
> 
>> im having problems when running python scripts
>> 
>> When running the scripts it always closes immediately

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


Re: Iterators, iterables and special objects

2020-07-21 Thread Terry Reedy

On 7/21/2020 5:32 AM, Peter Slížik wrote:

Hi list, two related questions:

1. Why do functions used to iterate over collections or dict members return
specialized objects like

type(dict.keys()) -> class 'dict_keys'
type(dict.values()) -> class 'dict_values'
type(dict.items()) -> class 'dict_items'
type(filter(..., ...)) -> class 'filter'
type(map(..., ...)) -> class 'map'
type(enumerate(...)) -> class 'enumerate'

instead of returning some more general 'iterable' and 'view' objects? Are
those returned objects really that different from one another that it makes
sense to have individual implementations?


Yes.  The dict views have to know how the dict is implemented to extract 
the keys, values, or pairs thereof.


The transformers each have different code. I suppose that each could 
instead pass a function to a generic 'transformer' class, but the 
indirection would just make execution slower and hide the specific info 
as to what the iterator is doing.



2. Why do these functions return iterators instead of iterables?


The view are iterables.  They can be iterated more than once and used in 
other operations.


The transformers should be once-through iterators because they can be 
passed once-through interators.  I suppose one could make them iterables 
and add an attribute 'pristine' set to True in __init__ and False in 
__iter__, but why have 2 objects instead of 1 when there is not gain in 
function?



First, I
find it confusing - to me, it is the loop's job to create an iterator from
the supplied iterable, and not the object that is being iterated over.


Python's design that iter(iterator) is iterator is extremely handy.

Note that iterators can be driven directly with next(), and not only 
indirectly with for...


Suppose line iterator 'file' has a header line with field names and 
multiple data lines.  One can do


it = iter(file)
fields = next(file)

for line in it:


Yes, one can add a flag variable 'first = True' and inside the loop
if first:
first = False
fields = line

but the 3 extra boilerplate lines add nothing.

And
second, with this design, iterators are required to be iterables too, which
is confusing as hell (at least for people coming from other languages in
which the distinction is strict).


I guess I was fortunate to not have to unlearn anything ;-).


--
Terry Jan Reedy


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


Re: Python Program Help

2020-07-21 Thread dn via Python-list

On 7/22/20 7:16 AM, Dennis Lee Bieber wrote:

On Tue, 21 Jul 2020 06:38:55 -0700 (PDT), ksikor14--- via Python-list
 declaimed the following:
Since this is apparently a homework assignment, I'm not going to
provide fixes -- just some comments.


Logic error?


(not entirely poking-fun: is a good learning opportunity for OP!)



(3) Prompt the user for data points. Data points must be in this format: 
string, int. Store the information before the comma into a string variable and 
the information after the comma into an integer. The user will enter -1 when 
they have finished entering data points. Output the data points. Store the 
string components of the data points in a list of strings. Store the integer 
components of the data points in a list of integers. (4 pts)


Ugh! Forgive my bluntness but WHO created that "enter -1" to signal the
end of the data input, especially when the input format is a string
followed by an integer, using a comma to differentiate the fields. Python
makes it so easy to use an /empty input line/ to signal end of data.


Am fairly sure that I've seen this question before - likely requiring 
implementation in another language. (FORTRAN, BASIC-Plus on a VAX or 
RSTS-machine c.1970s?)


Agreed, poor form old-chap - just not cricket, wot!



(4) Perform error checking for the data point entries. If any of the following 
errors occurs, output the appropriate error message and prompt again for a 
valid data point.

If entry has no comma
Output: Error: No comma in string. (1 pt)
If entry has more than one comma
Output: Error: Too many commas in input. (1 pt)
If entry after the comma is not an integer
Output: Error: Comma not followed by an integer. (2 pts)



Personally -- besides that I'd use an empty record to end input, I

processing-
Despite the fact that it would be an easy mistake for a user to make - 
pressing Enter? Would it not be better to require an active decision/action?




would NOT use "...:\n" in the prompt strings. To me it is much cleaner to
use "...: " as the prompt, which puts the input data on the same line.


+1
User Experience accounts for a significant proportion of the definition 
of 'success', for any project!




This coding style requires duplicating code... It also is relying on

...


That makes two places that need to be edited if a change is made to the
code. Especially if you try to sanitize the termination input. It is


+1



words = point.split(",")
if len(words) == 1:
print("Error: No comma in string.")
elif len(words) > 2:
print("Error: Too many commas in input. ")


Personally, I'd consider this an overly strict requirement -- I'd be
expecting the /last/ ", stuff" to be the integer, and anything prior to be
part of the author name ("Alexandre Dumas, Senior, 238")


Disagree - and one of the points of the exercise: Librarians have tomes 
inches-thick which discuss 'cataloging rules' - including where commas 
may, and may-not, be used!


Your point valid though, only the  comma has significance...
(at this time!)



It is apparent that no test is made to ensure names output are
shortened to the report format... One "improvement" would be to retain the
maximum name length (and maximum count) and adjust the output formatting to
fit those maximums.


Data should not be 'thrown away'! If the report-specification 'shortens' 
the data-field, then isn't that the purpose of output-formatting?


Given all the 'pretty', I'd suggest that the learning-objectives* 
include Python's string formatting language!


* um, er, given earlier comment about age/language, perhaps the words 
"should have" should have appeared in that sentence?

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


Re: Iterators, iterables and special objects

2020-07-21 Thread dn via Python-list

On 7/21/20 9:32 PM, Peter Slížik wrote:

Hi list, two related questions:

1. Why do functions used to iterate over collections or dict members return
specialized objects like

type(dict.keys()) -> class 'dict_keys'
type(dict.values()) -> class 'dict_values'
type(dict.items()) -> class 'dict_items'
type(filter(..., ...)) -> class 'filter'
type(map(..., ...)) -> class 'map'
type(enumerate(...)) -> class 'enumerate'

instead of returning some more general 'iterable' and 'view' objects? Are
those returned objects really that different from one another that it makes
sense to have individual implementations?


The key-word here is "light-weight"! (or is that two, words?)

These do not duplicate the keys/values in the dict (example), and thus 
have no (real) storage requirements (think thousands of values). We 
could think of them as an access channel or 'pipe' - they are a "view" 
of the data if you follow the database-terminology.


Another analogy is to "generators". A generator will yield successive 
data items, but will not compute or take storage resources for all of 
the values it will return, instead performing in a 'lazy' fashion or JiT 
(Just-in-time) delivery. Similarly, once a generator is "exhausted", it 
terminates. It cannot be re-used, without being re-computed.


For your reading pleasure: PEP 3106 -- Revamping dict.keys(), .values() 
and .items() https://www.python.org/dev/peps/pep-3106/




2. Why do these functions return iterators instead of iterables? First, I
find it confusing - to me, it is the loop's job to create an iterator from
the supplied iterable, and not the object that is being iterated over. And
second, with this design, iterators are required to be iterables too, which
is confusing as hell (at least for people coming from other languages in
which the distinction is strict).


This is a great question. (even if I'm motivated to say-so because it 
puzzled me too!) However, may I caution you not to expect that just 
because one language 'thinks' in a certain manner, that 
another/every-other language must do the same, eg in English we say 
"blue ball" but in other spoken-languages it may be expressed in the 
sequence "ball, blue". Which is correct? ...more correct?

(well, 'mine', of course! Cue Frank Sinatra: "I did it my way...")

Some more reading, which also under-pins and expands the above web.ref: 
https://docs.python.org/3/library/stdtypes.html



If 'everything' in Python is an "object", then some objects will contain 
multiple values. One would expect that these multiple values would be 
"iterable" (one could "iterate" over them). However, does the object 
provide a method to perform this iteration-function? If it does, then 
that object is also an "iterator"!


However, as @Terry explained, there is *no requirement* that a 
multi-valued object provide such a method.


Per above, the "return iterators instead of iterables" decision comes 
back to 'weight'. No 'copy' of the iterable object is made, only 
iterator functionality is provided, eg to a for-loop. It is also an 
example of Python's "we're all adults here" laissez-faire and dynamic 
philosophy: there is no rule that iterable <==> iterator!


A final thought for your consideration, is that Python considers 
functions (and methods) "first-class objects". Which means that they can 
be passed as arguments/parameters, for example. In some ways then, it 
may be helpful to think of an iterator (or generator) method as a 
function being passed to the for-loop's 'control function'.

(others may dislike this picture, so don't tell anyone I said-so...)


Further tutorials you may find helpful:
https://towardsdatascience.com/python-basics-iteration-and-looping-6ca63b30835c
https://www.w3schools.com/python/gloss_python_iterator_vs_iterable.asp
https://www.tutorialspoint.com/difference-between-python-iterable-and-iterator
https://www.python-course.eu/python3_iterable_iterator.php
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


True is True / False is False?

2020-07-21 Thread Tim Chase
I know for ints, cpython caches something like -127 to 255 where `is`
works by happenstance based on the implementation but not the spec
(so I don't use `is` for comparison there because it's not
guaranteed by the language spec). On the other hand, I know that None
is a single object that can (and often *should*) be compared using
`is`. However I spent some time reading through the language specs and
didn't encounter anything about booleans returned from
comparisons-operators, guaranteeing that they always return The One
True and The One False.

  x = 3 == 3 # some boolean expression evaluating to True/False
  y = 4 > 0 # another boolean expression
  if x is y:
print("cool, same as always")
  else:
print("is this ever possible?")

Is there some theoretical world in which that `else` branch could ever
be hit because the True referenced by x is not the same True
referenced by y? (assuming non-pathological overriding of dunder
methods to return true-ish or false-ish values; or at least assuming
any dunder-overriding is pure standard-library)

In the big picture, this is likely irrelevant and I should just use
"==" instead, but I got the question stuck in my head and ended up
bothered that I couldn't disinter an answer from docs.

Thanks,

-tkc




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


Re: True is True / False is False?

2020-07-21 Thread Chris Angelico
On Wed, Jul 22, 2020 at 11:04 AM Tim Chase
 wrote:
>
> I know for ints, cpython caches something like -127 to 255 where `is`
> works by happenstance based on the implementation but not the spec
> (so I don't use `is` for comparison there because it's not
> guaranteed by the language spec). On the other hand, I know that None
> is a single object that can (and often *should*) be compared using
> `is`. However I spent some time reading through the language specs and
> didn't encounter anything about booleans returned from
> comparisons-operators, guaranteeing that they always return The One
> True and The One False.

class bool(int)
 |  bool(x) -> bool
 |
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.

The docstring (shown here in "help(bool)") says clearly that you'll
only ever have those two instances and no others, so yes, it's a
language guarantee that you'll always get the exact same objects.

That said, though, a comparison isn't required to return a bool. If it
*does* return a bool, it has to be one of those exact two, but it
could return anything it chooses. But for built-in types and most
user-defined types, you will indeed get a bool.

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


How to limit *length* of PrettyPrinter

2020-07-21 Thread Stavros Macrakis
I see how to limit the *depth* in pretty-printing:

import pprint
pprint.PrettyPrinter(depth=2).pprint(((11,12,13),(21,22,23,(241,242,243),25,26,27)))
((11, 12, 13),
 (21, 22, 23, (...), 25, 26, 27))

But I would also like to limit the *length, *something like this:

pprint.PrettyPrinter(depth=2,length=4
).pprint(((11,12,13),(21,22,23,(241,242,243),25,26,27)))
((11, 12, 13),
 (21, 22, 23, (...), ...))   # Only show first 4 elements

How can I do that?

Thanks,

   -s

--

This is inspired by Lisp's *print-length*, e.g.:

(setq *print-level* 2 *print-length* 4)

'((11 12 13) (21 22 23 (241 242 243) 25 26 27))

((11 12 13)
 (21 22 23 # ...))
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to limit *length* of PrettyPrinter

2020-07-21 Thread dn via Python-list

On 7/22/20 1:31 PM, Stavros Macrakis wrote:

I see how to limit the *depth* in pretty-printing:

import pprint
pprint.PrettyPrinter(depth=2).pprint(((11,12,13),(21,22,23,(241,242,243),25,26,27)))
((11, 12, 13),
  (21, 22, 23, (...), 25, 26, 27))

But I would also like to limit the *length, *something like this:

pprint.PrettyPrinter(depth=2,length=4
).pprint(((11,12,13),(21,22,23,(241,242,243),25,26,27)))
((11, 12, 13),
  (21, 22, 23, (...), ...))   # Only show first 4 elements

How can I do that?



That's 'a bit of an ask' given that the four elements could be of any 
data-type (object)! Secondly, I'm having difficulty working-out how you 
wish to define "element".


1 Limit the input:
If you know the input, in the example it is nested tuple, then it would 
be trivial to slice the collection *before* passing to pprint, eg



t = ( 1, 2, 3, 4 )
t[ :2 ]

(1, 2)

pprint.pprint( t[ :2 ] )

(1, 2)

However, if the second element were an embedded collection, then that 
idea suffers a similar short-coming to the existing depth parameter!


1a
That said, if you also know the hierarchy, you could get really clever 
with a recursive function which 'pops' the first element from any given 
hierarchical construct, to the required number of elements. Sounds like 
a 'fun' (ie dastardly) project to assign coding trainees!
(this list doesn't accept graphic attachments otherwise I'd demonstrate 
my vicious grin...)


PS should you try this, would welcome a copy (off-list).


2 Limit the output:
Remember that the signature is:

class pprint.PrettyPrinter(indent=1, width=80, depth=None,
   stream=None, *, compact=False,
   sort_dicts=True)

How about capturing the stream output? Could you then post-process that 
by counting commas!

NB I have never tried capturing the stream o/p!

- or if you really want to 'go nuts', dust-off your polish notation and 
count opening and closing parentheses as well...


2a
One has to wonder though, why not grab the output stream and print only 
the first n-characters? (on the grounds that 'close-enough is 
good-enough'. However, it's your spec...)

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


"OSError: [Errno 9] Bad file descriptor" When I try to Install the library in conda prompt

2020-07-21 Thread Mathiyazhagan S
Dear Sir/Madam,
I'm new to the python program.

I'm trying to install the "numby" or anything to add into the library by
using the windows command prompt I'm getting some error please find the
attachment.

So please help me to resolve this issue.


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


Re: "OSError: [Errno 9] Bad file descriptor" When I try to Install the library in conda prompt

2020-07-21 Thread dn via Python-list

On 7/22/20 4:46 PM, Mathiyazhagan S wrote:

Dear Sir/Madam,
 I'm new to the python program.

I'm trying to install the "numby" or anything to add into the library by
using the windows command prompt I'm getting some error please find the
attachment.

So please help me to resolve this issue.


Unfortunately, this list does not accept non-text attachments. Please 
copy-paste the relevant messages directly into the email message. Please 
add information about your machine's OpSys, the Python version, etc.



Do you mean "numpy"?
Have you read the Conda instructions, Python docs, and the NumPy docs 
(if relevant)?

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