Jump to ratings and reviews
Rate this book

Python Tricks: A Buffet of Awesome Python Features

Rate this book
“I don’t even feel like I’ve scratched the surface of what I can do with Python” With Python The Book you’ll discover Python’s best practices and the power of beautiful & Pythonic code with simple examples and a step-by-step narrative. You'll get one step closer to mastering Python, so you can write beautiful and idiomatic code that comes to you naturally. Learning the ins and outs of Python is difficult—and with this book you'll be able to focus on the practical skills that really matter. Discover the “hidden gold” in Python’s standard library and start writing clean and Pythonic code today. Who Should Read This What Python Developers Say About The "I kept thinking that I wished I had access to a book like this when I started learning Python many years ago." — Mariatta Wijaya, Python Core Developer "This book makes you write better Python code!" — Bob Belderbos, Software Developer at Oracle "Far from being just a shallow collection of snippets, this book will leave the attentive reader with a deeper understanding of the inner workings of Python as well as an appreciation for its beauty." — Ben Felder, Pythonista "It's like having a seasoned tutor explaining, well, tricks!" — Daniel Meyer, Sr. Desktop Administrator at Tesla Inc.

326 pages, Kindle Edition

First published January 1, 2017

Loading interface...
Loading interface...

About the author

Dan Bader

8 books14 followers

Ratings & Reviews

What do you think?
Rate this book

Friends & Following

Create a free account to discover what your friends think of this book!

Community Reviews

5 stars
576 (55%)
4 stars
358 (34%)
3 stars
88 (8%)
2 stars
9 (<1%)
1 star
7 (<1%)
Displaying 1 - 30 of 97 reviews
Profile Image for Eric Nichols.
3 reviews7 followers
January 1, 2018
A quick read to fill in any gaps in your python knowledge

I'm an advanced python user and have worked at several startups, Google, and Microsoft, but I still found several tips in here that were new to me, and many others that I only knew because I'd learned them from colleagues when I worked at Google. For instance, I would usually just define an __str__ method on my custom classes and be lazy and not implement __repr__. But the book points out that if you want be lazy, just define __repr__ alone, as the default behavior of __str__ will call your __repr__ function anyway. I should have known this already but somehow it's a little thing I had missed when learning python. There are lots of bits of info like this: some you'll probably already know, but you might be surprised by a couple little tricks.

One outstanding feature of the book is a short recap after each section, giving simple rules of thumb to to follow. This cleared up a lot of uncertainty for me about some python best practices. I really like the book "Fluent Python" as well, but this one has more simple and practical suggestions and was a very quick read.

Highly recommended!
June 16, 2019
The Pythonite way from a very savvy user.
"-": Python 2 vs 3 difs.
"+": Short and up-to-the point style
"+": Lots of cool ideas
"+": Practical implications not just 'oh yeah there's something that works somehow in P'
"+": Good explanations
"+": Many examples
Profile Image for César Bustíos.
279 reviews101 followers
May 18, 2018
Putting the beginner stuff aside and the fact that I already knew most of the tricks, this is a well written book. Beautiful and simple.

Those iterator chains blew my mind.
Profile Image for Dimitrios Mistriotis.
Author 1 book43 followers
January 9, 2019
Wanted to check out this book so downloaded it. Most of the times I do this it ends up with me buying the actual book at the end so do not feel that guilty confessing this "habit". With "Python Tricks" was very early 100% sure that it would end up with a purchase which happened.

What I want from a coding book is always the same two things: (1) feel sad+happy while reading it: sad for parts of my codebase and happy that I am reading it, (2) Understand better patterns of the programming language and also be able to write better code, and if possible more idiomatic.

Book delivers both. immediately changed parts of some applications after reading the decorators chapter, while the PDF will be on my desktop folder ready to help change or write differently some parts of the current projects.

Some of the material has been posted on-line from the author but the book really delivers that extra which justifies a purchase from everyone coding in Python (in-my-not-so-humble-opinion). Last but not least if acquired from the book's site, https://realpython.com/products/pytho... , there are 12 (!) videos about the main concepts discussed with live coding sessions with author explaining the rationale behind each decision.
Profile Image for Ayush Goyal.
5 reviews
June 7, 2021
Even after working with python for almost 6 years now reading this book was actually very great! There are a huge number of concepts and things which you might have heard before or read somewhere else but you often don't use them regularly just because they didn't seep through your comfort at the start and now you actually forgot them.
This worked as good refresher for a lot many things.
Profile Image for Alfie Privat.
9 reviews
June 3, 2018

I have used python before but wanted to gain more advance knowledge. Fluent python is the Bible these days but it is too long (almost 800 pages). From my experience, you don’t need all language features to use a language affectively (think 80/20 rule). That is why this book was so appealing to me and it didn’t disappoint. If you want to save time and gain deeper insight into the python language, read this book.
Profile Image for Alireza Aghamohammadi.
56 reviews38 followers
November 17, 2021

مخاطب کتاب برنامه‌نویس‌های سطح متوسط و پیشرفته پایتون هستند. کتاب از هشت فصل تشکیل شده است که در هر فصل تعدادی فوت کوزه‌گری را در مورد پایتون به شما یاد می‌دهد. با اینکه خود من برنامه نویس حرفه‌ای پایتون هستم، باز هم نکاتی داشت که قبلا ندیده بودم. اگر میخواهید سطح دانش خودتان را نسبت به زبان برنامه نویسی پایتون افزایش دهید، کتاب فوق‌العاده‌ای است.
Profile Image for Rohit Goswami.
278 reviews71 followers
March 12, 2022
This is a fun, short read. There are a lot of nice tidbits here. Although there shouldn't be anything new for people with too much experience, it is still a nicely woven tale. I would have loved this ten years ago. The star rating in this case is also a testament to the warm and conversational tone Dan takes throughout the book, instead of the rather terse tone of most technical writing.
Profile Image for Jan Spörer.
46 reviews9 followers
January 14, 2020
Here are my key take-aways from the book (page numbers refer to the epup version of the book, I had 157 pages in total with my "14 screen size):
-Asserts are used to catch BUGS/unrecoverable errors, not erroneous user input, and make code more maintainable and help developers. Assets will just be ignored under certain circumstances and may pose a security risk when being relied upon in production. Never use it for data validation. Use "if + raise" for validation. (p. 14)
-Use a comma after the last item in a list. That helps to keep git diffs clean. (p. 19)
-Using "with" (context manager) for opening files is generally considered best practice as open files are closed automatically after leaving the with-statement. (p. 20)
Use trailing underscores to avoid name conflicts. Use double leading underscores for added functionality regarding name clash avoidance - Parent class variable is still available and not overwritten by child class; every class gets an explicit version of the variable (name mangling). (p. 25)
-Use single underscore to indicate that something is temporary or insignificant. (p. 28)
-Use literal string interpolation for string formatting: f'bla{}'. (p. 31)
-You can pass functions into functions. You can use the map-function to call the same function on a list of objects. You can define nested functions inside of functions and conditionally return them. (p. 37)
-You can make objects callable like a function by using the __call__ dunder method. (p. 39)
-Lambda functions are anonymous functions that can be called in the same line in that they are being defined. Lambdas are more restricted in their functionality. Often used in combination with the "sorted" function. But the use cases are very limited and it is mainly a trade-off between readability and conciseness. (p. 40)
-Decorators are wrappers for function definitions and are added by putting @decorator_name in front of the function definition. Decorated functions are different from the original functions. The decorator is only called at runtime. (p. 45)
-*args stands for positional arguments -> tuple, **kwargs stands for keyword arguments -> dict (p. 48)
-Use the "import functools", @functools.wraps decorator to copy lost function metadata to the decorator. You can use it for all decorators. (p. 49)
-Add *args and **kwargs to allow for optional parameters. (p. 51)
-Use function argument inpacking to directly pass a tuple or list without calling the individual elements. * for lists and tuples; ** for dictionaries. Dictionaries are automatically mapped to function parameter names . That helps to write more flexible interaces for modules and functions. (p. 53)
-”==” checks for equality while “is” checks for identity. If names point to the same object, it will evaluate as true. Copies won’t be true. (p. 56)
-__str__ is the readable string representation, __repr__ is the unambiguous debugging string representation. Optimally, the __repr__ be just inserted in Python code and restore the object’s state.
-Use custom exception classes that inherit from root Exception or subclasses: class NameTooShortError(ValueError): pass. (p. 62)
-Abstract Base Classes automatically raise NotImplementedError when child classes do not implement predefined functions, error thrown on instantiation (pp. 67-68)
-One can use @classmethods like so: @classmethod def prosciutto(cls: return cls([‘mozarella’, ‘tomatoes’, ‘ham’]) to make alternative constructor/__init__ methods with predefined inputs. (p. 79)
-@property decorator (p. 80)
-Use array.array as a more efficient option over lists when you only have one data type, arrays are “typed”. (p. 87)
-Lists can be used as stacks (LIFO) with O(1) time complexity, but shouldn’t be used as queues (FIFO), because then they have O(n) complexity. Collections.deques can handle LIFO and FIFO at O(1). (p. 97)
-List slicing with [start:end:step] (p. 109)
-Check if key is in dict by “if key in dict:” (p. 127)
-Sort dictionary keys using sorted(dict.items()). Sort by value using “sorted(dict.items(), key=lambda x: x[1]) -> You can even sort by absolute value: abs(x[1]) (p. 128)
-Use dir() to inspect libraries and see its classes and methods or use help(). (p. 142)
Profile Image for Bojan Tunguz.
407 reviews162 followers
January 11, 2020
A while ago, when I was still fairly new to Python, I stumbled upon the Dan Bader's "Real Python" newsletter. It was a very refreshing take on learning how to code. It gave a simple, yet insightful, tip each day. The approach and the substance were aimed at someone who is already familiar with the basics of Python and programming, but wanted to improve those skills in a non-formal and unsystematic way. 
So after a while I decided to purchase Dan's "Python Tricks" book. The book is written with the same general approach as the newsletter, yet there are a few big differences. For one, the book is written in a very systematic way, and walks you through various aspects of Python. It is broken into eight major sections, each containing several short-ish subsections. The subsections are similar to the newsletter emails, but go into more detail and depth. Even though the book follows a certain thematic progression, it is possible to read subsections out of order, and jump to the ones that seem most interesting to you at the time. One of the things I like the most about Dan's approach to Python exposition is that he tries to teach you not only how to do something, but also the rationale and the best practices behind different approaches. In this book you'll learn the why behind the how.
Python is a fairly high-level language, and its very legible and easy-to-understand style certainly help its enormous popularity. However, there are instances when understanding how it does things on a lower level helps, and this book nicely covers many of those cases. It pops the hood and takes a look at the engine. These are not just intellectual exercises, but can help you become a better coder. 
Regardless of your level of experience with Python (unless you are one of those 10x Ninja Rockstar Developers), this book will probably have something to teach you. Highly recommended.
Profile Image for Tim.
8 reviews1 follower
June 8, 2018
This was a great book to binge after attempting to read the wall-of-text that is Fluent Python. Python Tricks provides great insights into the language, while offering fun and digestible examples. Unfortunately, with the discrepancies between Python 2 and 3, it's not always the case that there's "one--and preferably only one--obvious way to do [things]"; however, Dan effectively provides the reader simple situational rules to follow in order to find the easiest/cleanest/most-Pythonic way of accomplishing a task.
2 reviews1 follower
July 30, 2020
Interesting introductions for advanced python concepts.
July 28, 2019
Book, which worth the time spent on it.

In general, this is a very good book for learning the Python programming language. There is either an experienced programmer or the only beginner is able to find something interesting and new for himself or strengthen his skills in the already known material and find out some features of the language.

The presentation of material here is great, so it reads lightly and you don't get tired of it, like of such books as Learn Python the Hard Way or Python Programming by Lutz.

Another big plus of the book is that it is up-to-date to the newest of Python, so it is another advantage in front of the above books.

Also, want to mark that this book has a pretty nice look and beautiful fonts, so reading becomes really a pleasure.

So I want definitely recommend this book. Yes, it is much more for already acquaintanced with Python readers, but still good for everyone.
March 16, 2022
This book was presented to me as the one with "advanced" topics for experienced Pythonistas. But I have to say, that very few chapters in that book seemed to me advanced - almost all was very known and very clear for me already. That means that either this is not really advanced Python book or that I'm more advanced Python programmer than I thought. Of course I hope it is the latter!

However the truth is that lot of discussed in this book is very useful and very helpful for day-to-day coding. And I must admit, that this is finally the first source which was able clearly explain to me how decorators actually works, so big thanks!

I have been coding along the reading, so if anybody is interested, here's the GitHub repo with complete code snippets from the book:

Happy Pythoning!
Profile Image for Mochammad Hadyan.
61 reviews3 followers
May 3, 2019
Love this book! Even for seasoned Python developer, you will be surprised how small, but exceptionally useful tricks that can help you to write Python code better.

Also, i found each chapter is fun to read in spite it is something i've already known before, because sometimes the contents radically change my paradigm when understanding the concept.

Last but not least, this can become one of the good reference book when you forget something about the Python concept (at least this is what i've done for the past months). Also, it really good resource to structure your learning when you want to go beyond basic Python.
1 review
December 5, 2019
Although the book is 300 pages, it's fairly short because of the big font. As the title says, there are a lot of tricks in this book. However, I already knew most of them from YouTube videos. Saying that, It's still a great book to have. The tone of the book is quite funny and keeps it interesting.
I have to say that this book is not for beginner. You should only pick this up once you are at least familiar with the language and all the basic objects (function, list, dictionary, set, string, ...). But it is definitely not as complicated as Fluent Python (by Luciano Ramalho). One more thing, some of the tricks in this book are widely known and used and they are expected in the industry.
Profile Image for Tony Poerio.
212 reviews11 followers
November 22, 2017
Good book. Concise and full and of helpful information, presented very simply. Doesn't get deep into the super-advanced language features (meta-programming, etc...). But provides very practical Python info that everyone can use on a daily basis in their programming.
Profile Image for Andrei.
61 reviews2 followers
June 26, 2018
A great book is like a long cheatsheet simple but extremely useful examples, you can read it fast due to the large sets of examples is a very practical especially if you read it before starting a new python project.
Profile Image for Ajitabh Pandey.
725 reviews38 followers
November 10, 2021
Even if you consider yourself an expert in python programming, you will still find something in this book which you may be reading for the first time. There is no need to read every chapter in sequence as every tip is independent. A good reference book for everybody programming in python.
Profile Image for Andy.
84 reviews
January 25, 2018
It was a really good book on python and even though I knew most of the stuff, I still got some bullets to solve some of my current python challenges.
Profile Image for O'Rety.
116 reviews9 followers
June 12, 2020
It's a good book written in a very friendly manner (maybe even too friendly - too much sugar can kill you), but I found it a little too shallow. It sweeps broadly, but has only <300 pages, so there's no place (and no intention) to go deeper. Again, maybe it is a good thing - that way it's more geared towards beginners who won't be too intimidated with the content. At least most of times, because it has it's not entirely balanced difficulty spikes (data structures section, min-heap, I'm looking at you).

Also, despite the broad sweeps, there's still a lot of topics that were left (structuring and packaging your programs, testing, .pyd and .pyi files, asyncio) or only got cursory glances (virtual environments). Some topics which are great fit for the format (dataclasses, walrus operator) are absent for the sole reason that they came to Python too late to get covered.

All in all it's a good advanced Python book geared more towards beginners (so it's a good fit between entry level books like Python Crash Course: A Hands-On, Project-Based Introduction to Programming or Automate the Boring Stuff with Python: Practical Programming for Total Beginners and more advanced ones like Effective Python: 90 Specific Ways to Write Better Python, Fluent Python: Clear, Concise, and Effective Programming or Python Cookbook (disclaimer I only read the first one on this list)).
43 reviews3 followers
December 3, 2019
This Python recipe targets neither the beginners nor the advanced users. Rather it is aimed towards people who have already mastered the syntax, using python for a while and want to take their skills to the next level. The author did an awesome job keeping it concise while touching a plethora of topics without making the whole thing boring!

Dive into the book if:

1. You are already familiar with basic python data structures (list, stack, set, dictionary, mutable and immutable objects).

2. You are comfortable with the object-oriented paradigm of python and want to take full advantage of python classes.

3. Want to know tricks to refactor and make your code more maintainable.
Profile Image for Tim.
71 reviews2 followers
November 29, 2020
If you are a beginner-to-intermediate Python enthusiast who is going at it alone, without any outside support whatsoever, as long as you have a basic understanding of how Python works and have already attempted a few projects on your own, this book is truly a gem and what you should be reading next. In a very condensed form, it manages to point out a whole lot of things you may have been doing wrong, or in a suboptimal way. In essence, it's like having a very good friend standing behind you and ever so gently correcting your course and giving very good advice. In all, this book is like a shortcut to the best Python programming practices. You still need to put work into making progress, but at least now you have a compass and a map. Can't recommend highly enough!
100 reviews
December 29, 2020
Took me a little bit over a year to read it... Which was good, if you try to read a programming book "in one session" you will forget what you read in the beginning.
I took my time, thought about each chapter and tried to apply it as soon as I read it - or at least think where I could apply it. Also, I'm not new to Python, so there were a lot of "tricks" I already know and use - but for those cases, I used the examples to verify that I really know it and it is always good to read someone else explaining it.

Overall, I do not agree to all "conclusions", but it is a really great book and I did recommend it to my team! So read it, but apply your own judgment and be cautious of what you apply to your own projects. In software engineering, there is not a single perfect solution. You need to see what fits your situation first.
25 reviews
February 2, 2023
Python Tricks is a fascinating book for intermediate Python developers that want to improve their skills. The book interestingly covers many topics of the language, from some basic concepts to advanced topics.

Some of the chapters that I specially enjoyed reading:

* Python's functions are cirst-class objects
* Every class needs a `__repr__`
* Defining your own exception (e.g. ConfigurationError)
* Deep copy and shallow copy
* NamedTuples
* Data structures: Stacks, Queues, Dequeues (double ended queues)
* List comprehensions
* Iterators
* Generators are simplified iterators
* Exploring Python modules with `dir()` and `help()`

The author explains the concepts with a very reasonable pace; slow enough to make them learnable, fast enough no to make things boarding.
41 reviews2 followers
June 9, 2023

I am a prior IBM employee & retiree. I coded in Fortran, 360 assembler, Cobal, RPG2 for S/3 and AS400 level systems, Visual Basic, C, C++, VBA for Access, Excel, Word, etc. I was always a "part time" programmer in a consulting role. I decided to tackle, or be tackled by, Python in my retirement. I know I am not saying anything that is unknown by stating Python is NOT an easy learn. But, I can also say that I am definitely enjoying the challenge. This book is my favorite of the many quality instruction offerings provided by Real Python. I know I will be re-reading this book many times over. Great job !
Profile Image for Frank.
1 review6 followers
March 22, 2019
Good book for intermediate Python developers

It is written in a very understandable but at the same time concise style. While it assumes the reader already has a decent understanding of programming in general and skips the basics, it gets pretty detailed in medium to advanced Python syntax, patterns and useful libraries; which makes it perfect for a developer experienced in another language, but relatively new to Python. If you really want to go beyond the basics, without having to swallow the entire Python oficial documentation, this book is for you.
Displaying 1 - 30 of 97 reviews

Can't find what you're looking for?

Get help and learn more about the design.