Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Expert Python Programming
Expert Python Programming

Expert Python Programming: Write professional, efficient and maintainable code in Python , Second Edition

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Expert Python Programming

Chapter 2. Syntax Best Practices – below the Class Level

The ability to write an efficient syntax comes naturally with time. If you take a look back at your first program, you will probably agree with this. The right syntax will appear to your eyes as a good-looking piece of code, and the wrong syntax as something disturbing.

Besides the algorithms that are implemented and the architectural design for your program, taking great care over how it is written weighs heavily on how it will evolve. Many programs are ditched and rewritten from scratch because of their obtuse syntax, unclear APIs, or unconventional standards.

But Python has evolved a lot in the last few years. So, if you were kidnapped for a while by your neighbor (a jealous guy from the local Ruby developers user group) and kept away from the news, you will probably be astonished by its new features. From the earliest version to the current one (3.5 at this time), a lot of enhancements have been made to make the...

Python's built-in types

Python provides a great set of datatypes. This is true for both numeric types and also collections. Regarding the numeric types, there is nothing special about their syntax. There are, of course, some differences for defining literals of every type and some (maybe) not well-known details regarding operators, but there aren't a lot of choices left for developers. Things change when it comes to collections and strings. Despite the "there should be only one way to do something" mantra, the Python developer is really left with plenty of choices. Some of the code patterns that seem intuitive and simple to beginners are often considered non-Pythonic by experienced programmers because they are either inefficient or simply too verbose.

Such Pythonic patterns for solving common problems (by many programmers called idioms) may often seem like only aesthetics. This cannot be more wrong. Most of the idioms are driven by the fact how Python is implemented...

Advanced syntax

It is hard to objectively tell which element of language syntax is advanced. For the purpose of this chapter on advanced syntax elements, we will consider the elements that do not directly relate to any specific built-in datatypes and which are relatively hard to grasp at the beginning. The most common Python features that may be hard to understand are:

  • Iterators
  • Generators
  • Decorators
  • Context managers

Iterators

An iterator is nothing more than a container object that implements the iterator protocol. It is based on two methods:

  • __next__: This returns the next item of the container
  • __iter__: This returns the iterator itself

Iterators can be created from a sequence using the iter built-in function. Consider the following example:

>>> i = iter('abc')
>>> next(i)
'a'
>>> next(i)
'b'
>>> next(i)
'c'
>>> next(i)
Traceback (most recent call last):
  File "<input>", line 1, in <module&gt...

Other syntax elements you may not know yet

There are some elements of the Python syntax that are not popular and rarely used. It is because they either provide very little gain or their usage is simply hard to memorize. Due to this, many Python programmers (even with years of experience) simply do not know about their existence. The most notable examples of such features are as follows:

  • The for … else clause
  • Function annotations

The for … else … statement

Using the else clause after the for loop allows you to execute a code of block only if the loop ended "naturally" without terminating with the break statement:

>>> for number in range(1):
...     break
... else:
...     print("no break")
...
>>>
>>> for number in range(1):
...     pass
... else:
...     print("break")
...
break

This comes in handy in some situations because it helps to remove some "sentinel" variables that may be required if the user wants...

Summary

This chapter covered various best syntax practices that do not directly relate to Python classes and object-oriented programming. The first part of the chapter was dedicated to syntax features around Python sequences and collections, strings and byte-related sequences were also discussed. The rest of the chapter covered independent syntax elements of two groups—those that are relatively hard to understand for beginners (such as iterators, generators, and decorators) and those that are simply less known (the for…else clause and function annotations).

Left arrow icon Right arrow icon

Key benefits

  • Based on the latest stable version of Python (version 3.5)
  • Creating well manageable code that will run in various environments with different sets of dependencies
  • Packed with advanced concepts and best practices to write efficient Python code

Description

Python is a dynamic programming language, used in a wide range of domains by programmers who find it simple, yet powerful. Even if you find writing Python code easy, writing code that is efficient and easy to maintain and reuse is a challenge. The focus of the book is to familiarize you with common conventions, best practices, useful tools and standards used by python professionals on a daily basis when working with code. You will begin with knowing new features in Python 3.5 and quick tricks for improving productivity. Next, you will learn advanced and useful python syntax elements brought to this new version. Using advanced object-oriented concepts and mechanisms available in python, you will learn different approaches to implement metaprogramming. You will learn to choose good names, write packages, and create standalone executables easily. You will also be using some powerful tools such as buildout and vitualenv to release and deploy the code on remote servers for production use. Moving on, you will learn to effectively create Python extensions with C, C++, cython, and pyrex. The important factors while writing code such as code management tools, writing clear documentation, and test-driven development are also covered. You will now dive deeper to make your code efficient with general rules of optimization, strategies for finding bottlenecks, and selected tools for application optimization. By the end of the book, you will be an expert in writing efficient and maintainable code.

Who is this book for?

The book would appeal to web developers and Python programmers who want to start using version 3.5 and write code efficiently. Basic knowledge of Python programming is expected.

What you will learn

  • Conventions and best practices that are widely adopted in the python community
  • Package python code effectively for community and production use
  • Easy and lightweight ways to automate code deployment on remote systems
  • Improve your code's quality, reliability, and performance
  • Write concurrent code in python
  • Extend python with code written in different languages

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 20, 2016
Length: 536 pages
Edition : 2nd
Language : English
ISBN-13 : 9781785884399
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : May 20, 2016
Length: 536 pages
Edition : 2nd
Language : English
ISBN-13 : 9781785884399
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 108.97
Expert Python Programming
€36.99
Modern Python Cookbook
€38.99
Modular Programming with Python
€32.99
Total 108.97 Stars icon
Banner background image

Table of Contents

15 Chapters
1. Current Status of Python Chevron down icon Chevron up icon
2. Syntax Best Practices – below the Class Level Chevron down icon Chevron up icon
3. Syntax Best Practices – above the Class Level Chevron down icon Chevron up icon
4. Choosing Good Names Chevron down icon Chevron up icon
5. Writing a Package Chevron down icon Chevron up icon
6. Deploying Code Chevron down icon Chevron up icon
7. Python Extensions in Other Languages Chevron down icon Chevron up icon
8. Managing Code Chevron down icon Chevron up icon
9. Documenting Your Project Chevron down icon Chevron up icon
10. Test-Driven Development Chevron down icon Chevron up icon
11. Optimization – General Principles and Profiling Techniques Chevron down icon Chevron up icon
12. Optimization – Some Powerful Techniques Chevron down icon Chevron up icon
13. Concurrency Chevron down icon Chevron up icon
14. Useful Design Patterns Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(4 Ratings)
5 star 50%
4 star 0%
3 star 25%
2 star 25%
1 star 0%
Facundo Batista Jul 03, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Disclaimer: I'm this book's technical reviewer.This book is a very good complement for medium or advanced Python developers, not because it will give hard core deep details of all Python internals, but because it delivers to the reader a broad range of subjects that makes the Python programmer a comprehensive developer, giving the ability of carrying forward complex projects in the real life day to day.Even so, this book explains several interesting subjects, not frequently addressed from the specific Python point of view, like concurrency, useful Python design patterns, or optimization.In the broader area, it addresses several subjects that are very related to Python programming but are not Python itself, like buildbots, packaging, test driven development, how to properly document your project, etc.In total, a valuable book for those that want to enhance their developing skills.
Amazon Verified review Amazon
giazax Jun 30, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book contains the best programming practices in Python for development of professional applications, with a focus on real-world code examples.Updated to the latest stable version of the language (Python 3.5), the book covers topics such as: Conventions and best practices adopted in the Python community, Python Package for production use, extend Python with other programming languages, concurrent python.Its authors are an experienced Python developers who also happens to be an excellent writers.Given my experience and goals, this book was a perfect read if you want to improve the quality and performance of your Python code.A good buy, recommended
Amazon Verified review Amazon
Jascha Casadio Dec 16, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I remember reading the first edition of this book some year ago. It was a nice read, which I enjoyed, despite not being among my favorite Python books. So that as soon as I saw that a new version was released, I changed my reading schedule to dive into this one. Overall, I cannot complaint. It's an average book which does cover topics that are more often than not left untouched by most Python titles available. On the other hand, I was expecting more than what the good old first edition provided. I must, of course, take into account the fact that practically all of the content of this bok was already known to me, which partially biases my final thought.The book is split into 14 chapters. It is well written and the discussion flows well through the paragraphs. While not native, the author writes down plain good English, which is something that must not be taken for granted in Packt Publishing books. The book starts with an introduciton on the current status of the language and the many problems v3 caused. An interesting chapter, even though it doesn't get as deep as it should. It then discusses best practices. Here I start having my first doubts: best practices are an excellent subject, no doubts. But the author ends up talking about concepts such as MRI and the abstract syntax tree. If you are a Python developer and never heard of them, do not worry. You won't really need them unless you are interested in the very core of the language, at which point this is not the book you are looking for.Several chapters we find later on are, again, interesting maybe, but probably not necessary. Chapter 4, for example, is about good names. Excellent. Now, given the fact that picking good names should be the first thing we learn as we start studying any programming language, the author often uses names related to ice creams or similar. Similarly, the chapters dedicated to managing the code, aka how to use Git, and documenting the code are not bad but, according to me, should not be here.From a book that should take the beginner Python developer into the next level I would expect coverage of topics such as distributing and deploying code, as well as concurrency. Generators. Debugging. Lambdas. Some of these concepts are discusses. Chapter 6, for example, covers the deployment of code. I enjoy it very much when an author discusses the 12-factor application concept, as well as when he provides good hints such as making sure the code runs in user space. Definitely my favorite chapter of the fourteen.Overall, not bad. Not among the best Python books out there, but not bad. Being happy with the first edition, I was expecting more. The real problem was not the quality of what has been provided, but according to me the choice of topics.I still suggest Fluid Python and Effective Python to anyone interested in advanced Python topics.
Amazon Verified review Amazon
Eric Osborne Sep 26, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
The technical content is OK but it was clearly never copyedited. It's got code typos, poorly crafted sentences, and I found at least one misspelling of 'Python'! I would expect this out of a $5 self-published copy-paste of a blog, not out of a Real Book from a Real Publisher.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.