fluentpython/example-code-2e

Runtime error in Example A-2 of First Edition

CavalcanteLucas opened this issue · 0 comments

I'm trying to run the Example A-2 (page 689) in the First Edition.
I'm not sure if it's something wrong that I'm doing.. but I read the code 10 times. I'm sure it is the same of the book.

I'm running this code as:

$python example_a_2__generate_array.py

where my Python version is 3.8.5. Then I see this error:

initial sample: 10500000 elements
Traceback (most recent call last):
  File "example_a_2__generate_array.py", line 19, in <module>
    with len(sample) < SAMPLE_LEN:
AttributeError: __enter__

Some reasoning:
I'm not reasigning the open function (as suggested here for one possible cause).

Possible solution:
Maybe line 19 should be replaced by:

if len(sample) < SAMPLE_LEN:

I tried that and got a good looking output:

initial sample: 10500000 elements
complete sample: 10500000 elements
not selected: 500000 samples
  writing not_selected.arr
selected: 10000000 samples
  writing selected.arr

And they seem to have been created correctly:

$ls -la *selected*
-rw-rw-r-- 1 lucas lucas  4000000 mai 13 14:57 not_selected.arr
-rw-rw-r-- 1 lucas lucas 80000000 mai 13 14:57 selected.arr

PS.: Thank you for the book and sharing your knowledge!