Text stringlengths 1 9.41k |
|---|
For more hints on this front,
though, watch for the _classtree.py inheritance tree climber we will write in_ Chapter 28, and the lister.py attribute listers and climbers we’ll code in Chapter 30.
###### Name Considerations in Tool Classes
One last subtlety here: because our AttrDisplay class in the classtools module ... |
As is, I’ve assumed that
client subclasses may want to use both its __str__ and gatherAttrs, but the latter of
these may be more than a subclass expects—if a subclass innocently defines a gather
```
Attrs name of its own, it will likely break our class, because the lower version in the
```
subclass will be used instea... |
If we really meant to provide a
```
__str__ only, though, this is less than ideal.
```
To minimize the chances of name collisions like this, Python programmers often prefix
methods not meant for external use with a single underscore: _gatherAttrs in our case.
This isn’t foolproof (what if another class defines _gather... |
Python automatically expands such
names to include the enclosing class’s name, which makes them truly unique. |
This is
a feature usually called pseudoprivate class attributes, which we’ll expand on in Chapter 30. |
For now, we’ll make both our methods available.
###### Our Classes’ Final Form
Now, to use this generic tool in our classes, all we need to do is import it from its
module, mix it in by inheritance in our top-level class, and get rid of the more specific
```
__str__ we coded before. |
The new print overload method will be inherited by instances
```
of Person, as well as Manager; Manager gets __str__ from Person, which now obtains it
from the `AttrDisplay coded in another module. |
Here is the final version of our`
_person.py file with these changes applied:_
_# File person.py (final)_
`from classtools import AttrDisplay` _# Use generic display tool_
```
class Person(AttrDisplay):
"""
Create and process person records
"""
def __init__(self, name, job=None, pay=0):
self.n... |
When we run this code now, we see all the attributes of our objects, not just
the ones we hardcoded in the original __str__. |
And our final issue is resolved: because
```
AttrDisplay takes class names off the self instance directly, each object is shown with
```
the name of its closest (lowest) class—tom displays as a Manager now, not a Person, and
we can finally verify that his job name has been correctly filled in by the `Manager`
construc... |
From a larger perspective, though, our
attribute display class has become a general tool, which we can mix into any class by
inheritance to leverage the display format it defines. |
Further, all its clients will automatically pick up future changes in our tool. |
Later in the book, we’ll meet even more
powerful class tool concepts, such as decorators and metaclasses; along with Python’s
introspection tools, they allow us to write code that augments and manages classes in
structured and maintainable ways.
###### Step 7 (Final): Storing Objects in a Database
At this point, our ... |
We now have a two-module system that not
only implements our original design goals for representing people, but also provides a
general attribute display tool we can use in other programs in the future. |
By coding
functions and classes in module files, we’ve ensured that they naturally support reuse.
And by coding our software as classes, we’ve ensured that it naturally supports
extension.
Although our classes work as planned, though, the objects they create are not real
database records. |
That is, if we kill Python, our instances will disappear—they’re transient objects in memory and are not stored in a more permanent medium like a file, so
they won’t be available in future program runs. |
It turns out that it’s easy to make
instance objects more permanent, with a Python feature called _object persistence—_
making objects live on after the program that creates them exits. |
As a final step in this
tutorial, let’s make our objects permanent.
**|**
-----
###### Pickles and Shelves
Object persistence is implemented by three standard library modules, available in every
Python:
```
pickle
```
Serializes arbitrary Python objects to and from a string of bytes
```
dbm (named anydbm in Pytho... |
They
provide powerful data storage options. |
Although we can’t do them complete justice in
this tutorial or book, they are simple enough that a brief introduction is enough to get
you started.
The pickle module is a sort of super-general object formatting and deformatting tool:
given a nearly arbitrary Python object in memory, it’s clever enough to convert the
o... |
The pickle module can handle almost any object you can create—lists, dictionaries, nested combinations thereof, and class instances. |
The latter are especially
useful things to pickle, because they provide both data (attributes) and behavior (methods); in fact, the combination is roughly equivalent to “records” and “programs.” Because pickle is so general, it can replace extra code you might otherwise write to create
and parse custom text file repres... |
By storing an object’s pickle
string on a file, you effectively make it permanent and persistent: simply load and unpickle it later to re-create the original object.
Although it’s easy to use pickle by itself to store objects in simple flat files and load
them from there later, the shelve module provides an extra laye... |
shelve translates an object to its pickled string with
```
pickle and stores that string under a key in a dbm file; when later loading, shelve fetches
```
the pickled string by key and re-creates the original object in memory with pickle. |
This
is all quite a trick, but to your script a shelve[*] of pickled objects looks just like a dic_tionary—you index by key to fetch, assign to keys to store, and use dictionary tools_
such as len, in, and dict.keys to get information. |
Shelves automatically map dictionary
operations to objects stored in a file.
In fact, to your script the only coding difference between a shelve and a normal dictionary is that you must open shelves initially and must close them after making changes.
The net effect is that a shelve provides a simple database for stori... |
It does
- Yes, we use “shelve” as a noun in Python, much to the chagrin of a variety of editors I’ve worked with over
the years, both electronic and human.
**|**
-----
not support query tools such as SQL, and it lacks some advanced features found in
enterprise-level databases (such as true transaction processing),... |
This is all simpler in Python
than in English, though, so let’s jump into some code.
Let’s write a new script that throws objects of our classes onto a shelve. |
In your text
editor, open a new file we’ll call makedb.py. Since this is a new file, we’ll need to import
our classes in order to create a few instances to store. |
We used from to load a class at
the interactive prompt earlier, but really, as with functions and other variables, there
are two ways to load a class from a file (class names are variables like any other, and
not at all magic in this context):
```
import person # Load class with import
bob = person... |
Copy or retype
this code to make instances of our classes in the new script, so we have something to
store (this is a simple demo, so we won’t worry about the test-code redundancy here).
Once we have some instances, it’s almost trivial to store them on a shelve. |
We simply
import the shelve module, open a new shelve with an external filename, assign the
objects to keys in the shelve, and close the shelve when we’re done because we’ve made
changes:
_# File makedb.py: store Person objects on a shelve database_
```
from person import Person, Manager # Load our classes
b... |
This is just
for convenience; in a shelve, the key can be any string, including one we might create
to be unique using tools such as process IDs and timestamps (available in the os and
```
time standard library modules). |
The only rule is that the keys must be strings and should
```
**|**
-----
be unique, since we can store just one object per key (though that object can be a list
or dictionary containing many objects). |
The values we store under keys, though, can
be Python objects of almost any sort: built-in types like strings, lists, and dictionaries,
as well as user-defined class instances, and nested combinations of all of these.
That’s all there is to it—if this script has no output when run, it means it probably
worked; we’re n... |
The actual files created can vary per platform, and just like in
the built-in open function, the filename in shelve.open() is relative to the current working directory unless it includes a directory path. |
Wherever they are stored, these files
implement a keyed-access file that contains the pickled representation of our three
Python objects. |
Don’t delete these files—they are your database, and are what you’ll
need to copy or transfer when you back up or move your storage.
You can look at the shelve’s files if you want to, either from Windows Explorer or the
Python shell, but they are binary hash files, and most of their content makes little sense
outside ... |
With Python 3.0 and no extra software installed, our database is stored in three files (in 2.6, it’s just one file, persondb, because
the bsddb extension module is preinstalled with Python for shelves; in 3.0, bsddb is a
third-party open source add-on):
_# Directory listing module: verify files are present_
```
>>> ... |
To verify our work better,
we can write another script, or poke around our shelve at the interactive prompt. |
Because shelves are Python objects containing Python objects, we can process them with
normal Python syntax and development modes. |
Here, the interactive prompt effectively
becomes a database client:
**|**
-----
```
>>> import shelve
```
`>>> db = shelve.open('persondb')` _# Reopen the shelve_
`>>> len(db)` _# Three 'records' stored_
```
3
```
`>>> list(db.keys())` _# keys is the index_
```
['Tom Jones', 'Sue Jones', 'Bob Smith'] #... |
For example, we can call bob’s lastName method freely, and
get his custom print display format automatically, even though we don’t have his
```
Person class in our scope here. |
This works because when Python pickles a class instance,
```
it records its self instance attributes, along with the name of the class it was created
from and the module where the class lives. |
When bob is later fetched from the shelve
and unpickled, Python will automatically reimport the class and link bob to it.
The upshot of this scheme is that class instances automatically acquire all their class
behavior when they are loaded in the future. |
We have to import our classes only to
make new instances, not to process existing ones. |
Although a deliberate feature, this
scheme has somewhat mixed consequences:
- The downside is that classes and their module’s files must be importable when an
instance is later loaded. |
More formally, pickleable classes must be coded at the top
level of a module file accessible from a directory listed on the `sys.path module`
search path (and shouldn’t live in the most script files’ module __main__ unless
they’re always in that module when used). |
Because of this external module file
requirement, some applications choose to pickle simpler objects such as dictionaries or lists, especially if they are to be transferred across the Internet.
**|**
-----
- The upside is that changes in a class’s source code file are automatically picked up
when instances of the ... |
For simple object storage, though, shelves and pickles
are remarkably easy-to-use tools.
###### Updating Objects on a Shelve
Now for one last script: let’s write a program that updates an instance (record) each
time it runs, to prove the point that our objects really are _persistent (i.e., that their_
current values ... |
The following file,
_updatedb.py, prints the database and gives a raise to one of our stored objects each time._
If you trace through what’s going on here, you’ll notice that we’re getting a lot of utility
“for free”—printing our objects automatically employs the general __str__ overloading
method, and we give raises b... |
This all
“just works” for objects based on OOP’s inheritance model, even when they live in a file:
_# File updatedb.py: update Person object on database_
```
import shelve
db = shelve.open('persondb') # Reopen shelve with same filename
for key in sorted(db): # Iterate to display database objects... |
Here it is in action, displaying all records and increasing
```
sue’s pay each time it’s run (it’s a pretty good script for sue...):
c:\misc> updatedb.py
Bob Smith => [Person: job=None, name=Bob Smith, pay=0]
Sue Jones => [Person: job=dev, name=Sue Jones, pay=100000]
Tom Jones => [Manager: job=mgr, nam... |
And once again, we can verify
our script’s work at the interactive prompt (the shelve’s equivalent of a database client):
```
c:\misc> python
>>> import shelve
```
`>>> db = shelve.open('persondb')` _# Reopen database_
`>>> rec = db['Sue Jones']` _# Fetch object by key_
```
>>> print(rec)
[Person: job=dev, nam... |
It stores a somewhat larger composite object in a flat file with pickle instead of shelve, but the effect
is similar. |
For more details on both pickles and shelves, see other books or Python’s
manuals.
###### Future Directions
And that’s a wrap for this tutorial. |
At this point, you’ve seen all the basics of Python’s
OOP machinery in action, and you’ve learned ways to avoid redundancy and its associated maintenance issues in your code. |
You’ve built full-featured classes that do real
work. |
As an added bonus, you’ve made them real database records by storing them in
a Python shelve, so their information lives on persistently.
There is much more we could explore here, of course. |
For example, we could extend
our classes to make them more realistic, add new kinds of behavior to them, and so on.
Giving a raise, for instance, should in practice verify that pay increase rates are between
zero and one—an extension we’ll add when we meet decorators later in this book. |
You
might also mutate this example into a personal contacts database, by changing the state
information stored on objects, as well as the class methods used to process it. |
We’ll
leave this a suggested exercise open to your imagination.
We could also expand our scope to use tools that either come with Python or are freely
available in the open source world:
_GUIs_
As is, we can only process our database with the interactive prompt’s commandbased interface, and scripts. |
We could also work on expanding our object database’s usability by adding a graphical user interface for browsing and updating its
records. |
GUIs can be built portably with either Python’s tkinter (Tkinter in 2.6)
**|**
-----
standard library support, or third-party toolkits such as WxPython and PyQt.
```
tkinter ships with Python, lets you build simple GUIs quickly, and is ideal for
```
learning GUI programming techniques; WxPython and PyQt tend to ... |
We might also implement a website for browsing and updating records,
instead of or in addition to GUIs and the interactive prompt. |
Websites can be
constructed with either basic CGI scripting tools that come with Python, or fullfeatured third-party web frameworks such as Django, TurboGears, Pylons,
web2Py, Zope, or Google’s App Engine. |
On the Web, your data can still be stored
in a shelve, pickle file, or other Python-based medium; the scripts that process it
are simply run automatically on a server in response to requests from web browsers
and other clients, and they produce HTML to interact with a user, either directly
or by interfacing with Framew... |
Such APIs return data in a more direct form, rather than
embedded in the HTML of a reply page.
_Databases_
If our database becomes higher-volume or critical, we might eventually move it
from shelves to a more full-featured storage mechanism such as the open source
ZODB object-oriented database system (OODB), or a more ... |
Python
itself comes with the in-process SQLite database system built-in, but other open
source options are freely available on the Web. |
ZODB, for example, is similar to
Python’s shelve but addresses many of its limitations, supporting larger databases,
concurrent updates, transaction processing, and automatic write-through on inmemory changes. |
SQL-based systems like MySQL offer enterprise-level tools for
database storage and may be directly used from a within a Python script.
_ORMs_
If we do migrate to a relational database system for storage, we don’t have to sacrifice Python’s OOP tools. |
Object-relational mappers (ORMs) like SQLObject and
SQLAlchemy can automatically map relational tables and rows to and from Python
classes and instances, such that we can process the stored data using normal Python
class syntax. |
This approach provides an alternative to OODBs like `shelve and`
ZODB and leverages the power of both relational databases and Python’s class
model.
**|**
-----
While I hope this introduction whets your appetite for future exploration, all of these
topics are of course far beyond the scope of this tutorial and this... |
If you
want to explore any of them on your own, see the Web, Python’s standard library
manuals, and application-focused books such as Programming Python. |
In the latter I
pick up this example where we’ve stopped here, showing how to add both a GUI and
a website on top of the database to allow for browsing and updating instance records.
I hope to see you there eventually, but first, let’s return to class fundamentals and finish
up the rest of the core Python language stor... |
We added constructors,
methods, operator overloading, customization with subclasses, and introspection
tools, and we met other concepts (such as composition, delegation, and polymorphism)
along the way.
In the end, we took objects created by our classes and made them persistent by storing
them on a shelve object datab... |
While exploring class basics, we also encountered multiple
ways to factor our code to reduce redundancy and minimize future maintenance costs.
Finally, we briefly previewed ways to extend our code with application-programming
tools such as GUIs and databases, covered in follow-up books.
In the next chapters of this pa... |
Before we move ahead, though, let’s
work through this chapter’s quiz to review what we covered here. |
Since we’ve already
done a lot of hands-on work in this chapter, we’ll close with a set of mostly theoryoriented questions designed to make you trace through some of the code and ponder
some of the bigger ideas behind it.
###### Test Your Knowledge: Quiz
1. |
When we fetch a Manager object from the shelve and print it, where does the display
format logic come from?
2. |
When we fetch a Person object from a shelve without importing its module, how
does the object know that it has a giveRaise method that we can call?
3. |
Why is it so important to move processing into methods, instead of hardcoding it
outside the class?
**|**
-----
4. |
Why is it better to customize by subclassing rather than copying the original and
modifying?
5. |
Why is it better to call back to a superclass method to run default actions, instead
of copying and modifying its code in a subclass?
6. |
Why is it better to use tools like `__dict__ that allow objects to be processed`
generically than to write more custom code for each type of class?
7. |
In general terms, when might you choose to use object embedding and composition
instead of inheritance?
8. |
How might you modify the classes in this chapter to implement a personal contacts
database in Python?
###### Test Your Knowledge: Answers
1. |
In the final version of our classes, Manager ultimately inherits its __str__ printing
method from AttrDisplay in the separate classtools module. |
Manager doesn’t have
one itself, so the inheritance search climbs to its Person superclass; because there
is no __str__ there either, the search climbs higher and finds it in AttrDisplay. |
The
class names listed in parentheses in a `class statement’s header line provide`
the links to higher superclasses.
2. |
Shelves (really, the pickle module they use) automatically relink an instance to the
class it was created from when that instance is later loaded back into memory.
Python reimports the class from its module internally, creates an instance with its
stored attributes, and sets the instance’s __class__ link to point to it... |
It’s important to move processing into methods so that there is only one copy to
change in the future, and so that the methods can be run on any instance. |
This is
Python’s notion of encapsulation—wrapping up logic behind interfaces, to better
support future code maintenance. |
If you don’t do so, you create code redundancy
that can multiply your work effort as the code evolves in the future.
4. Customizing with subclasses reduces development effort. |
In OOP, we code by
_customizing what has already been done, rather than copying or changing existing_
code. |
This is the real “big idea” in OOP—because we can easily extend our prior
work by coding new subclasses, we can leverage what we’ve already done. |
This is
much better than either starting from scratch each time, or introducing multiple
redundant copies of code that may all have to be updated in the future.
**|**
-----
5. |
Copying and modifying code doubles your potential work effort in the future, regardless of the context. |
If a subclass needs to perform default actions coded in a
superclass method, it’s much better to call back to the original through the superclass’s name than to copy its code. |
This also holds true for superclass constructors.
Again, copying code creates redundancy, which is a major issue as code evolves.
6. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.