Example code for the book Fluent Python, 1st Edition (O'Reilly, 2015)

Overview

Fluent Python, First Edition: example code

This repository is archived and will not be updated. Please visit https://github.com/fluentpython/example-code-2e

Example code for the book Fluent Python, First Edition by Luciano Ramalho (O'Reilly, 2015).

  • Code here may change and disappear without warning.
  • If a piece of code is not yet in the ebook, it's likely to be broken.
  • A major reorganization may happen when the last chapter is done.
  • No promises. No guarantees. Use at own risk.
Comments
  • Example 2-21 in book errors out in python 2.7

    Example 2-21 in book errors out in python 2.7

    # Example 2-21. Changing the value of an array item by poking one of its bytes
    import array
    numbers = array.array('h', [-2, -1, 0, 1, 2])
    memv = memoryview(numbers)
    

    Gives me this error:

    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-3-f1be3db9ba34> in <module>()
    ----> 1 memv = memoryview(numbers)
    
    TypeError: cannot make memory view because object does not have the buffer interface
    

    Based on research I did, this is a known limitation of python 2.7:

    An array can only expose its contents via the old-style buffer interface. This limitation does not apply to Python 3, where memoryview objects can be constructed from arrays, too. Array elements may be multi-byte values.

    Source: Python Docs

    This info might be useful to someone out there. Not sure if it's worth noting in a future revision of the book :)

    opened by robynsmith 2
  • Windows Specific Issue and work-around: Chapter 17: flags2_common.py

    Windows Specific Issue and work-around: Chapter 17: flags2_common.py

    First of all - a well written and complete book for intermediate to advanced Python users. It covers a lot of territory and for the most part will work as is on a variety of systems. I did find one bug in chapter 17 that prevents you from moving through the last part of the chapter. The error is in flags2_common.py on Windows 8-10: Not sure if this effects other systems too. The code provided is this...

    def main(download_many, default_concur_req, max_concur_req):
    
        args, cc_list = process_args(default_concur_req)
    
        actual_req = min(args.max_req, max_concur_req, len(cc_list))
    
        initial_report(cc_list, actual_req, args.server)
    
        base_url = SERVERS[args.server]
    
        t0 = time.time()
    
        counter = download_many(cc_list, base_url, args.verbose, actual_req)
    
        assert sum(counter.values()) == len(cc_list), \
    
            'some downloads are unaccounted for'
    
        final_report(cc_list, counter, t0)
    
    

    For windows, this will throw an error: This code works better...

    def main(download_many, default_concur_req, max_concur_req):
    
        args, cc_list = process_args(default_concur_req)
    
        actual_req = min(args.max_req, max_concur_req, len(cc_list))
    
        initial_report(cc_list, actual_req, args.server)
    
        base_url = SERVERS[args.server]
    
        t0 = time.time()
    
        counter = download_many(cc_list, base_url, args.verbose, actual_req)
    
        assert sum(counter.values()) == len(cc_list), 'some downloads are unaccounted for'
        
        final_report(cc_list, counter, t0)
    

    Let me know if you need clarification.

    opened by ghost 2
  • correct LookupError

    correct LookupError

    We are no longer inside of the BingoCage class, so we should change the LookupError's wording to reflect that this is an error within the new LotteryBlower class.

    opened by Destaq 1
  • Illegal copy of book found.

    Illegal copy of book found.

    Hello sir,

    @ramalho I found a GitHub repository with your book downloadable as a .pdf there. I don't know if you allowed that to be put up there, but if not then there's the link: https://github.com/EvanLi/programming-book-3/tree/master/Python

    This repository also has dozens of other O'Reilly books for download, not sure if that was intentional but would like to notify you nonetheless. Other than that, I have the paperback book and it is super useful, thank you!

    opened by Destaq 1
  • about the hash() function

    about the hash() function

    In Python3.7.4

    When I test to run this:

    >>> hash((1.000001))
    2305843009025
    >>> hash(1.000001)
    2305843009025
    >>> (1.000001) == 1.000001
    True
    >>> [1.000001] == 1.000001
    False
    

    But why:

    >>> frozenset({1.000001}) == 1.000001
    False
    >>> hash(frozenset({1.000001}))
    8757482414179413028
    

    float, tuple and frozenset are all hashable, why frozenset is special

    opened by mianyan-echo 1
  • bug in bulk_item_promo

    bug in bulk_item_promo

    https://github.com/fluentpython/example-code/blob/3d74f0e18344c2d257e00b689f4c7fe25b974952/06-dp-1class-func/promotions.py#L12

    += should be = if there were 10 item.quantity that bigger than 20 the total would be 0!

    opened by sigai 1
  • Tests should use a separate shelve test database

    Tests should use a separate shelve test database

    While trying to run the tests locally, I ran into errors when pickle tried to load the already existing database. I think it would be nice if readers do not have to waste any time with this error.

    This PR fixes that by creating a temporary database before any tests in the module run and deleting it afterwards. I also took the liberty of switching from the deprecated @pytest.yield_fixture to @pytest.fixture.

    Thanks for a wonderful book ๐Ÿ˜ƒ.

    opened by erika-dike 1
  • listcomp_speed.py will rasise a error in python2.7 and run well in python3.5

    listcomp_speed.py will rasise a error in python2.7 and run well in python3.5

    the code in listcomp_speed.py will rasise an syntax error: def clock(label, cmd): ... res = time.repeat(cmd, setup=SETUP, number=TIMES) ... print(label, *('{:3.f}.formart(x) for x in res')) File "", line 3 print(label, *('{:3.f}.formart(x) for x in res')) ^ SyntaxError: invalid syntax

    but it doesn't make sense to me, as the asterisk in print is unpacking, and unpacking is support in print, as print(*("1","2")) will work well.

    and the same code run well in python3.5.

    the book did not specify the environment of python.

    opened by wllbll 1
  • Running servers locally on docker

    Running servers locally on docker

    I was studying docker and used flags example to create and made changes do recreate servers with just one command. @ramalho you can try the instructions on README and check it out. If you like it we I can better reorganize the code ;)

    opened by renzon 1
  • improve Vector.__format__ to support * format specifier

    improve Vector.__format__ to support * format specifier

    Added support for * specifier in Vector.__format__ to show only small number of components by default, but all if * is specified. Creating this pull request was suggested in the soapbox at the end of Chapter 10.

    This request is open for suggestions or improvements and critique!

    opened by alekseirybalkin 1
  • Report an error on the file -- listcomp_speed.py

    Report an error on the file -- listcomp_speed.py

    My VSC runs listcomp_speed.py, it error when running print(label, *('{:.3f}'.format(x) for x in res)) ---- SyntaxError: Generator expression must be parenthesized

    opened by Tom-max-spec 0
  • Adding the ability to control length to __format__

    Adding the ability to control length to __format__

    Hello, I am a beginner of Python and github. I have just learned chapter 10 of Fluent Python. I noticed that in the last discussion section in chapter 10 you offered a little exercise in adding control over the length of output to the format method. I've just finished this exercise (although I feel like what I added looks jumbled) and added a few simple tests to the doctest (which may not be enough). I hope you can check whether the functions I added are correct. Meanwhile, I hope to take this opportunity to improve my python programming ability and practice the use of git and other functions. Thank you!

    opened by WeiGodHorse 1
  • Runtime error in Example A-2

    Runtime error in Example A-2

    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!

    opened by CavalcanteLucas 0
  • Update spinner_asyncio.py

    Update spinner_asyncio.py

    After that, I can see the rotation in Pycharm. Otherwise, nothing will be seen before "Answer: 42" appear. By the way, the original edition gives what we expected in Jupyter.

    opened by Austin0055 0
  • 11-iface-abc/tombola_runner.py fixture 'cls' not found

    11-iface-abc/tombola_runner.py fixture 'cls' not found

    my python version is 3.7.6, when I try running tombola_runner.py, it reports to me that: fixture 'cls' not found

    the error log is:

    file D:\huawei-code\github\example-code\11-iface-abc\tombola_runner.py, line 23
      def test(cls, verbose=False):
    E       fixture 'cls' not found
    >       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
    >       use 'pytest --fixtures [testpath]' for help on them.
    
    opened by anancds 0
Owner
Fluent Python
Support files for the O'Reilly books by Luciano Ramalho
Fluent Python
That is a example of a Book app on Python, made with support of all JS libraries on React framework

React+Python Books App You can use this repository whenever you want Used for a video Create the database: python -m dbutils Start the web server: pyt

Koma Human 1 Apr 20, 2022
This is the Halloween edition of my Flask Greeting App - HAPPY HALLOWEEEN EVERYONE! :)

HalloweenGreetingApp HAPPY HALLOWEEN EVERYONE! :) This is the Halloween Edition of my Flask Greeting App! Please note, this application is mean to be

Mariya 2 Feb 4, 2022
Open source book about making Python packages.

Python packages Tomas Beuzen & Tiffany Timbers Python packages are a core element of the Python programming language and are how you create organized,

Python Packages 169 Jan 6, 2023
This program tries to book a tennis court slot in either Southwark Park or Tanner Street Park in Southwark, London.

Book tennis courts in London This program tries to book a tennis court slot in either Southwark Park or Tanner Street Park in Southwark, London. Note:

Daniele 1 Jul 25, 2022
An example of Connecting a MySQL Database with Python Code

An example of Connecting a MySQL Database with Python Code And How to install Table of contents General info Technologies Setup General info In this p

Mohammad Hosseinzadeh 1 Nov 23, 2021
An example of Connecting a MySQL Database with Python Code

An example of Connecting And Query Data a MySQL Database with Python Code And How to install Table of contents General info Technologies Setup General

Mohammad Hosseinzadeh 1 Nov 23, 2021
Example python package with pybind11 cpp extension

Developing C++ extension in Python using pybind11 This is a summary of the commands used in the tutorial.

null 55 Sep 4, 2022
Python Example Project Structure

Python Example Project Structure Example of statuses that can be in readme: Visit my docs for the full documentation, examples and guides. With this p

null 1 Oct 31, 2021
An example of python package

An example of python package Why use packages? It is a good practice to not code the same function twice, and to reuse common code from one python scr

null 10 Oct 18, 2022
Buffer overflow example for python

Buffer overflow example for python

Mehmet 1 Jan 4, 2022
This is a survey of python's async concurrency features by example.

Survey of Python's Async Features This is a survey of python's async concurrency features by example. The purpose of this survey is to demonstrate tha

Tyler Lovely 4 Feb 10, 2022
Packages of Example Data for The Effect

causaldata This repository will contain R, Stata, and Python packages, all called causaldata, which contain data sets that can be used to implement th

null 103 Dec 24, 2022
An example using debezium and mysql with docker-compose

debezium-mysql An example using debezium and mysql with docker-compose The docker compose starts the Zookeeper, Kafka, Mysql and Debezium Connect. Aft

Horรกcio Dias Baptista Neto 4 May 21, 2022
This is an example manipulation package of for a robot manipulator based on Drake with ROS2.

This is an example manipulation package of for a robot manipulator based on Drake with ROS2.

Sotaro Katayama 1 Oct 21, 2021
BOHB tune library template (included example)

BOHB-template ์‹คํ–‰ ๋ฐฉ๋ฒ• python main.py 2021-10-10 ๊ธฐ์ค€ tf keras ๋ฒ„์ „ (tunecallback ๋ฐฉ์‹) ์™„๋ฃŒ tf gradienttape ๋ฒ„์ „ (train_iteration ๋ฐฉ์‹) ์™„๋ฃŒ pytorch ๋ฒ„์ „์€ ๊ตฌํ˜„ ์ค€๋น„์ค‘ ๋ฐฉ๋ฒ• ์†Œ๊ฐœ

Seungwoo Han 5 Mar 24, 2022
Assembly example for CadQuery

Spindle and vacuum attachment This is a model of the vacuum attachment for my Workbee CNC router. There is a mist spray coming from the left hand side

Marcus Boyd 20 Sep 16, 2022
An example file showing a simple endpoints like a login/logout function and maybe some others.

Flask API Example An example project showing a simple endpoints like a login/logout function and maybe some others. How to use: Open up your IDE (or u

Kevin 1 Oct 27, 2021
Script to produce `.tex` files of example GAP sessions

Introduction The main file GapToTex.py in this directory is used to produce .tex files of example GAP sessions. Instructions Run python GapToTex.py [G

Friedrich Rober 2 Oct 6, 2022
An example project that shows how to check if a certain macro is active in a file.

PlatformIO Check Compiler Flags Example Description Demonstrates the usage of an extra script and a special compilter invocation to get the active mac

Maximilian Gerhardt 1 Oct 28, 2021