Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Python Unlocked
Python Unlocked

Python Unlocked: Become more fluent in Python—learn strategies and techniques for smart and high-performance Python programming

eBook
$31.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.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

Python Unlocked

Chapter 2. Namespaces and Classes

In the previous chapter, we covered how objects worked. In this chapter, we will explore how objects are made available to code via reference, specifically how namespaces work, what modules are, and how they are imported. We will also cover topics related to classes, such as language protocols, MRO, and abstract classes. We will discuss the following topics:

  • Namespaces
  • Imports and modules
  • Class multiple inheritance, MRO, super
  • Protocols
  • Abstract classes

How referencing objects work – namespaces

Key 1: Interrelations between objects.

The scope is the visibility of a name within a code block. Namespace is mapping from names to objects. Namespaces are important in order to maintain localization and avoid name collision. Every module has a global namespace. Modules store mapping from variable name to objects in their __dict__ attribute, which is a normal Python dictionary along with information to reload it, package information, and so on.

Every module's global namespace has an implicit reference to the built-in module; hence, objects that are in the built-in module are always available. We can also import other modules in the main script. When we use the syntax import module name, a mapping with module name to module object is created in the global namespace of the current module. For import statements with syntax such as import modname as modrename, mapping is created with a new name to module object.

We are always in the __main__...

Functions with state – closures

Key 2: Creating cheap state-remembering functions.

A closure is a function that has access to variables in an enclosing scope, which has completed its execution. This means that referenced objects are kept alive until the function is in memory. The main utility of such a setup is to easily retain some state, or to create specialized functions whose functioning depends on the initial setup:

>>> def getformatter(start,end):
...     def formatter(istr):
...         print("%s%s%s"%(start,istr,end))
...     return formatter
... 
>>> formatter1 = getformatter("<",">")
>>> formatter2 = getformatter("[","]")
>>> 
>>> formatter1("hello")
<hello>
>>> formatter2("hello")
[hello]
>>> formatter1.__closure__[0].cell_contents
'>'
>>> formatter1.__closure__[1].cell_contents
'<'

We can do...

Understanding import and modules

Key 3: Creating a custom loader for modules.

Import statements get references of other module objects in the current module's namespace. It consists of searching the module, executing code to create a module object, updating caches (sys.modules), updating modules namespace, and creating a reference to new module being imported.

The built-in __import__ function searches and executes the module to create a module object. The importlib library has the implementation, and it also provides a customizable interface to the import mechanism. Various classes interact to get the job done. The __import__ function should return a module object. For example, in the following example, we are creating a module finder, which checks for modules in any path that is given as an argument during construction. Here, an empty file named names.py should be present at the given path. We have loaded the module, then inserted its module object in sys.modules and added a function...

Class inheritance

We already discussed how instances and classes are created. We also discussed how attributes are accessed in a class. Let's dive deeper into how this works for multiple base classes. As type is searched for the presence of an attribute for an instance, if the type inherits from a number of classes, they all are searched as well. There is a defined pattern to this (Method Resolution Order (MRO)). This order plays an important role in determining the method in cases of multiple inheritance and diamond-shaped inheritance.

Method resolution order

Key 4: Understanding MRO.

The methods are searched in the base classes of a class in predefined manner. This sequence or order is known as method resolution order. In Python 3, when an attribute is not found in a class, it is searched in all the base classes of that class. If the attribute is still not found, the base classes of the base classes are searched. This process goes on until we exhaust all base classes. This is similar...

Using language protocols in classes

All objects that provide a specific functionality have certain methods that facilitate that behavior, for example, you can create an object of type worker and expect it to have the submit_work(function, kwargs), and is _completed() methods. Now, we can expect all objects that have these methods to be usable as workers in any application portion. Similarly, the Python language has defined some methods that are needed to add a certain functionality to an object. If an object possesses these methods, it has that functionality.

We will discuss two very import protocols: iteration protocol, and context protocol.

Iteration protocol

For iteration protocol, objects must possess the __iter__ method. If the object possesses it, we can use the object anywhere that we use an iterator object. When we are using the iterator object in a for loop or passing it to the iter built-in function, we are calling its __iter__ method. This method returns another or the same object...

How referencing objects work – namespaces


Key 1: Interrelations between objects.

The scope is the visibility of a name within a code block. Namespace is mapping from names to objects. Namespaces are important in order to maintain localization and avoid name collision. Every module has a global namespace. Modules store mapping from variable name to objects in their __dict__ attribute, which is a normal Python dictionary along with information to reload it, package information, and so on.

Every module's global namespace has an implicit reference to the built-in module; hence, objects that are in the built-in module are always available. We can also import other modules in the main script. When we use the syntax import module name, a mapping with module name to module object is created in the global namespace of the current module. For import statements with syntax such as import modname as modrename, mapping is created with a new name to module object.

We are always in the __main__ module's...

Functions with state – closures


Key 2: Creating cheap state-remembering functions.

A closure is a function that has access to variables in an enclosing scope, which has completed its execution. This means that referenced objects are kept alive until the function is in memory. The main utility of such a setup is to easily retain some state, or to create specialized functions whose functioning depends on the initial setup:

>>> def getformatter(start,end):
...     def formatter(istr):
...         print("%s%s%s"%(start,istr,end))
...     return formatter
... 
>>> formatter1 = getformatter("<",">")
>>> formatter2 = getformatter("[","]")
>>> 
>>> formatter1("hello")
<hello>
>>> formatter2("hello")
[hello]
>>> formatter1.__closure__[0].cell_contents
'>'
>>> formatter1.__closure__[1].cell_contents
'<'

We can do the same by creating a class and using the instance object to save state. The benefit with closures...

Left arrow icon Right arrow icon

Key benefits

  • *Write smarter, bug-free, high performance code with minimal effort
  • *Uncover the best tools and options available to Python developers today
  • *Deploy decorators, design patters, and various optimization techniques to use Python 3.5 effectively

Description

Python is a versatile programming language that can be used for a wide range of technical tasks—computation, statistics, data analysis, game development, and more. Though Python is easy to learn, it’s range of features means there are many aspects of it that even experienced Python developers don’t know about. Even if you’re confident with the basics, its logic and syntax, by digging deeper you can work much more effectively with Python – and get more from the language. Python Unlocked walks you through the most effective techniques and best practices for high performance Python programming - showing you how to make the most of the Python language. You’ll get to know objects and functions inside and out, and will learn how to use them to your advantage in your programming projects. You will also find out how to work with a range of design patterns including abstract factory, singleton, strategy pattern, all of which will help make programming with Python much more efficient. Finally, as the process of writing a program is never complete without testing it, you will learn to test threaded applications and run parallel tests. If you want the edge when it comes to Python, use this book to unlock the secrets of smarter Python programming.

Who is this book for?

If you are a Python developer and you think that you don’t know everything about the language yet, then this is the book for you. We will unlock the mysteries and re-introduce you to the hidden features of Python to write efficient programs, making optimal use of the language.

What you will learn

  • *Manipulate object creation processes for instances, classes, and functions
  • *Use the best possible language constructs to write data structures with super speed and maintainability
  • *Make efficient use of design patterns to decrease development time and make your code more maintainable
  • *Write better test cases with an improved understanding of the testing framework of Python and unittests, and discover how to develop new functionalities in it
  • *Write fully-optimized code with the Python language by profiling, compiling C modules, and more
  • *Unlock asynchronous programming to build efficient and scalable applications

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Last updated date : Feb 11, 2025
Publication date : Dec 30, 2015
Length: 172 pages
Edition : 1st
Language : English
ISBN-13 : 9781785881312
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

Last updated date : Feb 11, 2025
Publication date : Dec 30, 2015
Length: 172 pages
Edition : 1st
Language : English
ISBN-13 : 9781785881312
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 136.97
Mastering Python
$43.99
Python GUI Programming Cookbook
$48.99
Python Unlocked
$43.99
Total $ 136.97 Stars icon

Table of Contents

9 Chapters
1. Objects in Depth Chevron down icon Chevron up icon
2. Namespaces and Classes Chevron down icon Chevron up icon
3. Functions and Utilities Chevron down icon Chevron up icon
4. Data Structures and Algorithms Chevron down icon Chevron up icon
5. Elegance with Design Patterns Chevron down icon Chevron up icon
6. Test-Driven Development Chevron down icon Chevron up icon
7. Optimization Techniques Chevron down icon Chevron up icon
8. Scaling Python 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 Empty star icon Empty star icon 3
(2 Ratings)
5 star 50%
4 star 0%
3 star 0%
2 star 0%
1 star 50%
Eduardo j. Morales Jan 16, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The inners of the interpreter are explained clearly and mind opening to more. Concise and specific.
Amazon Verified review Amazon
Jascha Casadio Jul 23, 2016
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
And yet another Python book. Being such a clean and flexible has brought this 20 years old programming language to be one of the hottest ones out there. Like it or not, most of the active repositories on GitHub are on Python. This is also confirmed by multiple sources listing the most demanded programming languages in the IT world. We Pythonists are lucky because, apart from a nice documentation, there is plenty of books to pick from, even though most of them cover basic features of the language. Python Unlocked does not belong to this large group of titles and focuses itself on intermediate topics.Released at the end of 2015, Python Unlocked is a short book targeting that niche of Pythonists interested in intermediate to advanced topics, such as decorators, abstract classes and unit testing.Let's dive into the content!The very first things that comes to the eye of the reader is poor English writing skills. True, Packt Publishing does not offer authors any kind of proofreading service but someone should at least check if articles are present. The reader, sometimes after a second pass through the sentence, can still grasp what the author wanted to say, but this definitely lowers the overall quality of the title.English apart, the choice of topics somehow got me raising an eyebrow in doubt: abstract classes are definitely a subject an intermediate Python developer wants to know of, but the MRO is probably misplaced here. Unless you are going to work in the core of the language itself, and are smart enough to prefer mixins to multiple inheritance, you can definitely live without knowing about it.Unnecessary complexities are present everywhere. So are unclear explanations. For example, the book starts discussing the internals of an object. The author states When an attribute is searched in an object first, it is searched in its dictionary then its type's (base class's) dictionary. Fine, but what is that __dict__ that I see everywhere? Either you introduce me to it, and explain me what it is or, if I am supposed to know what it represents already then the whole chapter is superfluous.Let's continue. Decorators are callable objects, which replace the original callable objects with some other objects. This is not correct. A decorator can replace the original callable with another one, but it must not. No words about decorators with a variable number of arguments, which is a very interesting aspect of decorators. Only later on, paged ahead, the author dedicates a couple of lines explaining functools.wrap.The examples are usually very short, Hello world! like pieces of code, whose functions are given names like f1, f2 and foo and whose body does little more than print('adf').Overall, a poor effort. The concepts are not properly explained and the examples are too short and focused on unnecessary complexities. Anyone interested in intermediate to advanced Python topics should pick any of the following titles, instead:Fluent PythonEffective Python: 59 Specific Ways to Write Better PythonAs usual, you can find more reviews on my personal blog: books.lostinmalloc.com. Feel free to pass by and share your thoughts!
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.

Modal Close icon
Modal Close icon