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
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781785886850
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : May 20, 2016
Length: 536 pages
Edition : 2nd
Language : English
ISBN-13 : 9781785886850
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 96.97 108.97 12.00 saved
Expert Python Programming
€36.99
Modern Python Cookbook
€26.99 €38.99
Modular Programming with Python
€32.99
Total 96.97 108.97 12.00 saved 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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.