100% found this document useful (12 votes)
104 views

Full Download Professional Python 1st Edition Luke Sneeringer PDF

Sneeringer

Uploaded by

iminrimann
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (12 votes)
104 views

Full Download Professional Python 1st Edition Luke Sneeringer PDF

Sneeringer

Uploaded by

iminrimann
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Get ebook downloads in full at ebookname.

com

Professional Python 1st Edition Luke Sneeringer

https://ebookname.com/product/professional-python-1st-
edition-luke-sneeringer/

OR CLICK BUTTON

DOWNLOAD EBOOK

Explore and download more ebook at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

3D Game Environments Create Professional 3D Game Worlds


Luke Ahearn

https://ebookname.com/product/3d-game-environments-create-
professional-3d-game-worlds-luke-ahearn/

Beginning python from novice to professional 2nd


Edition Magnus Lie Hetland

https://ebookname.com/product/beginning-python-from-novice-to-
professional-2nd-edition-magnus-lie-hetland/

Python Interviews Discussions with Python Experts 1st


Edition Mike Driscoll

https://ebookname.com/product/python-interviews-discussions-with-
python-experts-1st-edition-mike-driscoll/

Advances in Agronomy Vol 90 1st Edition Donald L.


Sparks (Ed.)

https://ebookname.com/product/advances-in-agronomy-vol-90-1st-
edition-donald-l-sparks-ed/
Forensic Dentistry Second Edition David R. Senn

https://ebookname.com/product/forensic-dentistry-second-edition-
david-r-senn/

The Fifth Freedom Jobs Politics and Civil Rights in the


United States 1941 1972 Anthony S. Chen

https://ebookname.com/product/the-fifth-freedom-jobs-politics-
and-civil-rights-in-the-united-states-1941-1972-anthony-s-chen/

Scotland Eyewitness Travel Guides Juliet Clough

https://ebookname.com/product/scotland-eyewitness-travel-guides-
juliet-clough/

Imperial Lineages and Legacies in the Eastern


Mediterranean Recording the Imprint of Roman Byzantine
and Ottoman Rule 18 Birmingham Byzantine and Ottoman
Studies 1st Edition Rhoads Murphey (Editor)
https://ebookname.com/product/imperial-lineages-and-legacies-in-
the-eastern-mediterranean-recording-the-imprint-of-roman-
byzantine-and-ottoman-rule-18-birmingham-byzantine-and-ottoman-
studies-1st-edition-rhoads-murphey-editor/

Phytochemicals Nutrient Gene Interactions 1st Edition


Mark S. Meskin

https://ebookname.com/product/phytochemicals-nutrient-gene-
interactions-1st-edition-mark-s-meskin/
Giant Micelles Properties and Applications 1st Edition
Raoul Zana

https://ebookname.com/product/giant-micelles-properties-and-
applications-1st-edition-raoul-zana/
PROFESSIONAL PYTHON®

INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv

▸ PART I FUNCTIONS
CHAPTER 1 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
CHAPTER 2 Context Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
CHAPTER 3 Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

▸ PART II CLASSES
CHAPTER 4 Magic Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
CHAPTER 5 Metaclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
CHAPTER 6 Class Factories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
CHAPTER 7 Abstract Base Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

▸ PART III DATA


CHAPTER 8 Strings and Unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
CHAPTER 9 Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

▸ PART IV EVERYTHING ELSE


CHAPTER 10 Python 2 Versus Python 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
CHAPTER 11 Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
CHAPTER 12 CLI Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
CHAPTER 13 asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
CHAPTER 14 Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
PROFESSIONAL

Python®
PROFESSIONAL

Python®

Luke Sneeringer
Professional Python®
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2016 by John Wiley & Sons, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-1-119-07085-6
ISBN: 978-1-119-07083-2 (ebk)
ISBN: 978-1-119-07078-8 (ebk)

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers,
MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the
Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201)
|748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including
without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or
promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is
sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional ser-
vices. If professional assistance is required, the services of a competent professional person should be sought. Neither the
publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred
to in this work as a citation and/or a potential source of further information does not mean that the author or the pub-
lisher endorses the information the organization or Web site may provide or recommendations it may make. Further, read-
ers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work
was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with stan-
dard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such
as a CD or DVD that is not included in the version you purchased, you may download this material at http://
booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2015952564

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade-
marks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other countries,
and may not be used without written permission. Python is a registered trademark of Python Software Foundation. All
other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product
or vendor mentioned in this book.
To Meagan. My loving wife, and forever my best
friend. You make “happily ever after” a reality.
ABOUT THE AUTHOR

LUKE SNEERINGER has designed, architected, built, and contributed to numerous Python applica-
tions for companies including FeedMagnet, May Designs, and Ansible, and is a frequent speaker at
Python conferences. He lives in Austin, Texas, with his wife, Meagan, and a non-trivial contingent
of cats and fish.

ABOUT THE TECHNICAL EDITORS

ALAN GAULD is a certified Enterprise Architect for The Open Group Architecture Framework
(TOGAF), working in the telecommunications and customer service industries. He has been
programming since 1974 and using Python since 1998. He is the author of two books on Python.
When not working, he enjoys hiking, photography, travel, and music.
ELIAS BACHAALANY is a computer programmer, software reverse engineer, and a technical writer.
Elias has also co-authored the books Practical Reverse Engineering (Wiley, 2014) and The Antivirus
Hacker’s Handbook (Wiley, 2015). During his employment period at Hex-Rays S.A, he amped up
IDA Pro’s scripting facilities and contributed to the IDAPython project.
CREDITS

PROJECT EDITOR PROFESSIONAL TECHNOLOGY & STRATEGY


Kevin Shafer DIRECTOR
Barry Pruett
TECHNICAL EDITOR
Alan Gauld; Elias Bachaalany BUSINESS MANAGER
Amy Knies
PRODUCTION EDITOR
Joel Jones ASSOCIATE PUBLISHER
Jim Minatel
COPY EDITOR
Kimberly A. Cofer PROJECT COORDINATOR, COVER
Brent Savage
MANAGER OF CONTENT DEVELOPMENT &
ASSEMBLY PROOFREADER
Mary Beth Wakefield Kathryn Duggan

PRODUCTION MANAGER INDEXER


Kathleen Wisor Jack Lewis

MARKETING DIRECTOR COVER DESIGNER


David Mayhew Wiley

MARKETING MANAGER COVER IMAGE


Carrie Sherrill ©Getty Images/Yagi Studio
ACKNOWLEDGMENTS

THIS BOOK WOULD NOT be a reality without the indispensible help of its editor, Kevin Shafer, and
technical reviewers, Alan Gould and Elias Bachaalany. Their efforts made this book immeasurably
better (and substantially reduced errata contained therein). The entire team at Wiley did an out-
standing job of taking my rather unattractive starting manuscripts and making something beautiful.
A special thanks goes to Jason Ford, my dear friend and the brilliant entrepreneur who gives me
an endless supply of entertaining work. He gave me my fi rst opportunity to write Python profes-
sionally, and continues to be a daily source of interesting problems, fascinating debate, and endless
excitement (oh, and a paycheck).
I am grateful also to many friends both inside and outside the Python community, who have worked
or played with me over the past many years. While these are sadly too many to list, conscience
would not forgive a failure to note a subset by name: Mickie Betz, Frank Burns, David Cassidy,
Jon Chappell, Diana Clarke, George Dupere, John Ferguson, Alex Gaynor, Jasmin Goedtel, Chris
Harbison, Boyd Hemphill, Rob Johnson, Daniel Lindsley, Jeff McHale, Doug Napleone, Elli Pope,
Tom Smith, and Caleb Sneeringer.
Thanks to my parents, Jim and Cheryl Sneeringer, who taught me more things than I could ever
enumerate. Among these was how to code, but greatest in importance was how to live.
Finally, the acknowledgements could hardly be considered complete without a paragraph citing the
support, dedication, and love of my wife, Meagan. She convinced me that this book was worth writ-
ing, and graciously supported me during every step of the process. I could not be more blessed or
more thankful to have her in my life every day.

—Soli Deo Gloria


CONTENTS

INTRODUCTION xxv

PART I: FUNCTIONS

CHAPTER 1: DECORATORS 3

Understanding Decorators 3
Decorator Syntax 4
Order of Decorator Application 5
Where Decorators Are Used 6
Why You Should Write Decorators 6
When You Should Write Decorators 7
Additional Functionality 7
Data Sanitization or Addition 7
Function Registration 7
Writing Decorators 7
An Initial Example: A Function Registry 7
Execution-Time Wrapping Code 9
A Simple Type Check 9
Preserving the help 10
User Verification 11
Output Formatting 12
Logging 14
Variable Arguments 15
Decorator Arguments 16
How Does This Work? 17
The Call Signature Matters 18
Decorating Classes 20
Type Switching 22
A Pitfall 24
Summary 25

CHAPTER 2: CONTEXT MANAGERS 27

What Is a Context Manager? 27


Context Manager Syntax 28
The with Statement 28
The enter and exit Methods 28
Exception Handling 29
CONTENTS

When You Should Write Context Managers 30


Resource Cleanliness 30
Avoiding Repetition 31
Propagating Exceptions 31
Suppressing Exceptions 32
A Simpler Syntax 37
Summary 38
CHAPTER 3: GENERATORS 41

Understanding What a Generator Is 41


Understanding Generator Syntax 41
The next Function 43
The StopIteration Exception 45
Python 2 46
Python 3 47
Communication with Generators 47
Iterables Versus Iterators 49
Generators in the Standard Library 50
range 50
dict.items and Family 50
zip 51
map 51
File Objects 52
When to Write Generators 53
Accessing Data in Pieces 53
Computing Data in Pieces 54
Sequences Can Be Infinite 54
When Are Generators Singletons? 54
Generators within Generators 55
Summary 56

PART II: CLASSES


CHAPTER 4: MAGIC METHODS 59

Magic Method Syntax 59


Available Methods 60
Creation and Destruction 61
__init__ 61
__new__ 62
__del__ 62

xvi
CONTENTS

Type Conversion 63
__str__, __unicode__, and __bytes__ 63
__bool__ 64
__int__, __float__, and __complex__ 65
Comparisons 65
Binary Equality 65
Relative Comparisons 67
Operator Overloading 68
Overloading Common Methods 71
Collections 75
Other Magic Methods 77
Summary 77
CHAPTER 5: METACLASSES 79

Classes and Objects 79


Using type Directly 80
Creating a Class 81
Creating a Subclass 81
The type Chain 82
The Role of type 82
Writing Metaclasses 83
The new Method 83
new Versus init 83
A Trivial Metaclass 84
Metaclass Inheritance 84
Using Metaclasses 87
Python 3 87
Python 2 88
What About Code That Might Run on Either Version? 88
When Is Cross-Compatibility Important? 89
When to Use Metaclasses 89
Declarative Class Declaration 89
An Existing Example 89
How This Works 90
Why This Is a Good Use for Metaclasses 91
Class Verification 91
Non-Inheriting Attributes 93
The Question of Explicit Opt-In 94
Meta-Coding 95
Summary 97

xvii
CONTENTS

CHAPTER 6: CLASS FACTORIES 99

A Review of type 99
Understanding a Class Factory Function 100
Determining When You Should Write Class Factories 102
Runtime Attributes 102
Understanding Why You Should Do This 103
Attribute Dictionaries 104
Fleshing Out the Credential Class 104
The Form Example 105
Dodging Class Attribute Consistency 106
Class Attributes Versus Instance Attributes 107
The Class Method Limitation 108
Tying This in with Class Factories 109
Answering the Singleton Question 109
Summary 111

CHAPTER 7: ABSTRACT BASE CLASSES 113

Using Abstract Base Classes 113


Declaring a Virtual Subclass 115
Why Declare Virtual Subclasses? 115
Using register as a Decorator 117
__subclasshook__ 117
Declaring a Protocol 119
Other Existing Approaches 119
Using NotImplementedError 120
Using Metaclasses 120
The Value of Abstract Base Classes 122
Abstract Properties 124
Abstract Class or Static Methods 125
Built-in Abstract Base Classes 126
Single-Method ABCs 126
Alternative-Collection ABCs 127
Using Built-In Abstract Base Classes 128
Additional ABCs 128
Summary 128

PART III: DATA


CHAPTER 8: STRINGS AND UNICODE 131

Text String Versus Byte String 131


String Data in Python 132
Python 3 Strings 132
xviii
CONTENTS

Python 2 Strings 134


six 136
Strings with Non-ASCII Characters 136
Observing the Difference 136
Unicode Is a Superset of ASCII 137
Other Encodings 137
Encodings Are Not Cross-Compatible 138
Reading Files 139
Python 3 139
Specifying Encoding 139
Reading Bytes 140
Python 2 140
Reading Other Sources 141
Specifying Python File Encodings 141
Strict Codecs 143
Suppressing Errors 143
Registering Error Handlers 144
Summary 145

CHAPTER 9: REGULAR EXPRESSIONS 147

Why Use Regular Expressions? 147


Regular Expressions in Python 148
Raw Strings 148
Match Objects 149
Finding More Than One Match 149
Basic Regular Expressions 150
Character Classes 150
Ranges 151
Negation 151
Shortcuts 152
Beginning and End of String 153
Any Character 154
Optional Characters 154
Repetition 155
Repetition Ranges 155
Open-Ended Ranges 156
Shorthand 156
Grouping 157
The Zero Group 159
Named Groups 159
Referencing Existing Groups 160
Lookahead 161
Flags 163
xix
CONTENTS

Case Insensitivity 163


ASCII and Unicode 163
Dot Matching Newline 163
Multiline Mode 164
Verbose Mode 164
Debug Mode 164
Using Multiple Flags 165
Inline Flags 165
Substitution 165
Compiled Regular Expressions 166
Summary 167

PART IV: EVERYTHING ELSE


CHAPTER 10: PYTHON 2 VERSUS PYTHON 3 171

Cross-Compatibility Strategies 171


The __future__ Module 172
2to3 172
Writing Changes 173
Limitations 174
six 174
Changes in Python 3 175
Strings and Unicode 175
The print Function 176
Division 176
Absolute and Relative Imports 177
Removal of “Old-Style” Classes 178
Metaclass Syntax 179
six.with_metaclass 179
six.add_metaclass 180
Exception Syntax 180
Handling Exceptions 181
Exception Chaining 181
Dictionary Methods 182
Function Methods 183
Iterators 183
Standard Library Relocations 184
Merging “Fast” Modules 184
io 184
pickle 184
The URL Modules 185
Renames 185
Other Package Reorganizations 185
xx
CONTENTS

Version Detection 186


Summary 186
CHAPTER 11: UNIT TESTING 187

The Testing Continuum 187


The Copied Ecosystem 188
The Isolated Environment 188
Advantages and Disadvantages 189
Speed 189
Interactivity 189
Testing Code 190
Code Layout 190
Testing the Function 191
The assert Statement 192
Unit Testing Frameworks 192
Running Unit Tests 193
Failures 193
Errors 194
Skipped Tests 195
Loading Tests 196
Mocking 197
Mocking a Function Call 197
Asserting Mocked Calls 199
Inspecting Mocks 201
Call Count and Status 201
Multiple Calls 202
Inspecting Calls 203
Other Testing Tools 203
coverage 203
tox 204
Other Test Runners 205
Summary 205

CHAPTER 12: CLI TOOLS 207

optparse 207
A Simple Argument 207
name == ‘ main__’ 208
OptionParser 208
Options 209
Types of Options 209
Adding Options to OptionParser 209

xxi
CONTENTS

Options with Values 210


Non-String Values 211
Specifying Option Values 212
Positional Arguments 214
Counters 214
List Values 215
Why Use optparse? 216
argparse 216
The Bare Bones 217
Arguments and Options 217
Option Flags 217
Alternate Prefixes 218
Options with Values 219
Positional Arguments 222
Reading Files 223
Why Use argparse? 224
Summary 224

CHAPTER 13: ASYNCIO 225

The Event Loop 225


A Simple Event Loop 226
Running the Loop 226
Registering Tasks and Running the Loop 227
Delaying Calls 227
Partials 228
Running the Loop until a Task Completes 228
Running a Background Loop 229
Coroutines 230
Nested Coroutines 231
Futures and Tasks 232
Futures 232
Tasks 232
Callbacks 234
No Guarantee of Success 235
Under the Hood 235
Callbacks with Arguments 235
Task Aggregation 236
Gathering Tasks 236
Waiting on Tasks 237
Timeouts 238
Waiting on Any Task 239
Waiting on an Exception 239

xxii
CONTENTS

Queues 240
Maximum Size 242
Servers 242
Summary 244
CHAPTER 14: STYLE 245

Principles 245
Assume Your Code Will Require Maintenance 245
Be Consistent 246
Think About Ontology, Especially with Data 246
Do Not Repeat Yourself 246
Have Your Comments Explain the Story 247
Occam’s Razor 247
Standards 248
Trivial Rules 248
Documentation Strings 248
Blank Lines 249
Imports 249
Variables 250
Comments 250
Line Length 251
Summary 251

INDEX 253

xxiii
INTRODUCTIO N

THIS BOOK INTRODUCES THE READER to more advanced Python programming by providing an
intermediate course in the Python language.
Recently, Python has become more and more frequently the developer’s language of choice. It is used
all over the world, for myriad purposes. As adoption continues to increase, more and more develop-
ers are spending their days writing Python.
Python has grown so steadily precisely because it is a very powerful language, and even many seasoned
Python developers have only scratched the surface of what the language is capable of doing.

WHO THIS BOOK IS FOR


This book is for developers who have already worked in Python, are already familiar with the
language, and desire to learn more about it. This book assumes that readers have already done
most basic tasks involved with developing in Python (such as having used the Python interactive
terminal).
If you are a reader who seeks a general survey of intermediate to advanced Python language
features, you should read this book from start to fi nish.
Alternatively, you may be a reader who has used some more-advanced language features in
passing, or potentially needs to maintain code that uses such features. Consider using this
book as a reference guide or index to flesh out your understanding when you are grappling with a
particular implementation.

WHAT THIS BOOK COVERS


This book covers all recent versions of Python (including both Python 2 and Python 3). At the time
of this writing, the most recent version available is Python 3.4, and Python 3.5 is in beta. This book
primarily covers Python 2.6, 2.7, 3.3, and 3.4. Most code is provided in a manner that will run on
both Python 2 and Python 3, with Python 2 code specifically noted as such.
Additionally, this book includes a chapter with a deep dive into distinctions between Python 2 and
Python 3, which provides advice on writing code to run on multiple versions of Python, as well as
porting over to Python 3.
This book primarily focuses on two areas. The fi rst is features of the language itself. For example,
this book includes several chapters about various aspects of how Python’s class and object model
works. The second area is modules provided as part of the standard library. For example, this book
includes a chapter each on modules such as asyncio, unittest, and argparse.
INTRODUCTION

HOW THIS BOOK IS STRUCTURED


This book is essentially divided into four parts.
The fi rst three chapters in the book are fundamentally about functions in Python. This part includes
a chapter each on decorators and context managers, which are reusable ways to modify or wrap
functions to add functionality. It also includes a chapter on generators, which are a way to design
functions that yield values one at a time, rather than creating an entire list of values in advance and
returning them in one block.
The second part comprises the next four chapters, and they are all related somehow to Python
classes and the language’s object model. There is a chapter on magic methods. Then, there is a
chapter each on metaclasses and class factories, which are two approaches to constructing classes in
powerful ways. Finally, a chapter on abstract base classes explains the abc module and how to make
classes declare patterns that they implement.
The third part comprises two chapters about strings and data. There is a chapter on how to navigate
using Unicode strings (as opposed to byte strings) in Python, which also covers in detail how strings
differ between Python 2 and Python 3. There is also a chapter on regular expressions, which covers
the Python re module as well as how to write regular expressions.
Finally, the fourth part covers everything that does not neatly fit into one of the fi rst three parts.
This part begins with an in-depth look at the distinctions between Python 2 and Python 3, and
how to write code that is interoperable with both. There is a chapter on unit testing, focusing on
the unittest module. A chapter on command-line interface (CLI) tools teaches you about both
optparse and argparse, which are Python’s modules for writing command-line tools. There is a
chapter on asyncio, which is a new asynchronous programming library that was added to the stan-
dard library in Python 3.4. Finally, the book closes with a chapter on style.

WHAT YOU NEED TO USE THIS BOOK


You will, fi rst and foremost, need a machine running Python.
Although it does not make a difference in most chapters, this book is slightly Linux-focused in its
approach (this will be most relevant in the chapter on CLI tools). Examples were run in a Linux
environment, and output may vary slightly on Windows.

CONVENTIONS
To help you get the most from the text and keep track of what’s happening, we’ve used a number of
conventions throughout the book.

xxvi
INTRODUCTION

WARNING Boxes like this one hold important, not-to-be forgotten information
that is directly relevant to the surrounding text.

NOTE Notes, tips, hints, tricks, and asides to the current discussion are offset
and placed in italics like this.

As for styles in the text:


➤ We highlight new terms and important words when we introduce them.
➤ We show keyboard strokes like this: Ctrl+A.
➤ We show filenames, URLs, and code within the text like so: persistence.properties.
➤ We present code as follows:

We use a monofont type for most code examples.

ERRATA
We make every effort to ensure that there are no errors in the text or in the code. However, no one
is perfect, and mistakes do occur. If you fi nd an error in one of our books (like a spelling mistake
or faulty piece of code), we would be very grateful for your feedback. By sending in errata, you may
save another reader hours of frustration and, at the same time, you will be helping us to provide
even higher quality information.
To fi nd the errata page for this book, go to http://www.wrox.com and locate the title using the
Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On
this page, you can view all errata that has been submitted for this book and posted by Wrox editors.
A complete book list (including links to each book’s errata) is also available at www.wrox.com/
misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/
techsupport.shtml and complete the form there to send us the error you have found. We’ll check
the information and, if appropriate, post a message to the book’s errata page and fix the problem in
subsequent editions of the book.

P2P.WROX.COM
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based
system for you to post messages relating to Wrox books and related technologies, and to interact
with other readers and technology users. The forums offer a subscription feature to e-mail you

xxvii
INTRODUCTION

topics of interest of your choosing when new posts are made to the forums. Some Wrox authors, edi-
tors, other industry experts, and your fellow readers are present on these forums.
At http://p2p.wrox.com, you will fi nd a number of different forums that will help you not only as
you read most Wrox books, but also as you develop your own applications. To join the forums, just
follow these steps:
1. Go to p2p.wrox.com and click the Register link.
2. Read the terms of use and click Agree.
3. Complete the required information to join, as well as any optional information you wish to
provide, and click Submit.
4. You will receive an e-mail with information describing how to verify your account and
complete the joining process.

NOTE You can read messages in the forums without joining P2P. However, in
order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read
messages at any time on the web. If you would like to have new messages from a particular forum
e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to
questions about how the forum software works, as well as many common questions specific to P2P
and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

xxviii

flast.indd 09/21/2015 Page xxviii


PART I
Functions
1
Decorators
A decorator is a tool for wrapping code around functions or classes. Decorators then explicitly
apply that wrapper to functions or classes to cause them to “opt in” to the decorator’s func-
tionality. Decorators are extremely useful for addressing common prerequisite cases before
a function runs (for example, ensuring authentication), or ensuring cleanup after a function
runs (for example, output sanitization or exception handling). They are also useful for taking
action on the decorated function or class itself. For example, a decorator might register a func-
tion with a signaling system or a URI registry in web applications.
This chapter provides an overview of what decorators are and how they interact with Python
functions and classes. It enumerates certain decorators that appear in the Python standard
library. Finally, it offers instruction in writing decorators and attaching them to functions
and classes.

UNDERSTANDING DECORATORS
At its core, a decorator is a callable that accepts a callable and returns a callable. A decorator
is simply a function (or other callable, such as an object with a __call__ method) that accepts
the decorated function as its positional argument. The decorator takes some action using that
argument, and then either returns the original argument or some other callable (presumably
that interacts with it in some way).
Because functions are fi rst-class objects in Python, they can be passed to another function just
as any other object can be. A decorator is just a function that expects another function, and
does something with it.
This sounds more confusing than it actually is. Consider the following very simple decorator.
It does nothing except append a line to the decorated callable’s docstring.
def decorated_by(func):
func.__doc__ += '\nDecorated by decorated_by.'
return func
4 ❘ CHAPTER 1 DECORATORS

Now, consider the following trivial function:


def add(x, y):
"""Return the sum of x and y."""
return x + y

The function’s docstring is the string specified in the fi rst line. It is what you will see if you run help
on that function in the Python shell. Here is the decorator applied to the add function:
def add(x, y):
"""Return the sum of x and y."""
return x + y
add = decorated_by(add)

Here is what you get if you run help:


Help on function add in module __main__:

add(x, y)
Return the sum of x and y.
Decorated by decorated_by.
(END)

What has happened here is that the decorator made the modification to the function’s __doc__
attribute, and then returned the original function object.

DECORATOR SYNTAX
Most times that developers use decorators to decorate a function, they are only interested in
the fi nal, decorated function. Keeping a reference to the undecorated function is ultimately
superfluous.
Because of this (and also for purposes of clarity), it is undesirable to define a function, assign it to
a particular name, and then immediately reassign the decorated function to the same name.
Therefore, Python 2.5 introduced a special syntax for decorators. Decorators are applied by
prepending an @ character to the name of the decorator and adding the line (without the implied
decorator’s method signature) immediately above the decorated function’s declaration.
Following is the preferred way to apply a decorated_by decorator to the add method:
@decorated_by
def add(x, y):
"""Return the sum of x and y."""
return x + y

Note again that no method signature is being provided to @decorated_by. The decorator is
assumed to take a single, positional argument, which is the method being decorated. (You will
see a method signature in some cases, but with other provided arguments. This is discussed later
in this chapter.)
This syntax allows the decorator to be applied where the function is declared, which makes it easier
to read the code and immediately realize that the decorator is in play. Readability counts.

c01.indd 09/21/2015 Page 4


Decorator Syntax ❘ 5

Order of Decorator Application


When is a decorator applied? When the @ syntax is being used, decorators are applied immediately
after the decorated callable is created. Therefore, the two examples shown of how to apply deco-
rated_by to add are exactly equivalent. First, the add function is created, and then, immediately
after that, it is wrapped with decorated_by.
One important thing to note about this is that it is possible to use multiple decorators on a single
callable (just as it is possible to wrap function calls multiple times).
However, note that if you use multiple decorators using the @ syntax, they are applied in order, from
bottom to top. This may be counterintuitive at fi rst, but it makes sense given what the Python inter-
preter is actually doing.
Consider the following function with two decorators applied:
@also_decorated_by
@decorated_by
def add(x, y):
"""Return the sum of x and y."""
return x + y

The fi rst thing that occurs is that the add function is created by the interpreter. Then, the deco-
rated_by decorator is applied. This decorator returns a callable (as all decorators do), which is
then sent to also_decorated_by, which does the same; the latter result is assigned to add.
Remember that the application of decorated_by is syntactically equivalent to the following:
add = decorated_by(add)

The previous two-decorator example is syntactically equivalent to the following:


add = also_decorated_by(decorated_by(add))

In both cases, the also_decorated_by decorator comes fi rst as a human reads the code. However,
the decorators are applied bottom to top for the same reason that the functions are resolved from
innermost to outermost. The same principles are at work.
In the case of a traditional function call, the interpreter must fi rst resolve the inner function call in
order to have the appropriate object or value to send to the outer call.
add = also_decorated_by(decorated_by(add)) # First, get a return value for
# `decorated_by(add)`.
add = also_decorated_by(decorated_by(add)) # Send that return value to
# `also_decorated_by`.

With a decorator, fi rst the add function is created normally.


@also_decorated_by
@decorated_by
def add(x, y):
"""Return the sum of x and y."""
return x + y
Another Random Document on
Scribd Without Any Related Topics
The Project Gutenberg eBook of No time for
Toffee!
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: No time for Toffee!

Author: Henry Farrell

Release date: July 27, 2021 [eBook #65931]

Language: English

Credits: Greg Weeks, Mary Meehan and the Online Distributed


Proofreading Team at http://www.pgdp.net

*** START OF THE PROJECT GUTENBERG EBOOK NO TIME FOR


TOFFEE! ***
NO TIME FOR TOFFEE!
By Charles F. Myers

Life was Marc's oyster, but: subversives


had shot him—a ghost was ready to haunt his
corpse—and Toffee was loving him to death!

[Transcriber's Note: This etext was produced from


Imagination Stories of Science and Fantasy
July 1952
Extensive research did not uncover any evidence that
the U.S. copyright on this publication was renewed.]
Just as he stepped to the microphone Marc caught sight of the
swarthy man. He saw the red scar across the left eyebrow, the dull
flash of metal in the large hairy hand. By then it was too late even to
cry out. In the next instant the glass panel in the control booth
shattered.
Marc felt an explosion of hot pain deep inside his chest. He was
aware of looking around dumbly at Dick Drewson and seeing
Drewson's face register shocked disbelief. Then the scene—the room,
Drewson and the others—disappeared, engulfed in a blinding sheet of
flame—and Marc knew he was falling....

Somewhere, in a place where time and space didn't exist, grey mists
began to seeth and swirl, and withall there was an ominous rumbling.
The High Council was almost in session.
In a sense, the High Council was already in session, for the Heads of
the Council had developed their intellects to such an inconceivable
degree that when a meeting of the Council was imminent they could
send their thoughts on ahead of them and get the meeting under
way even before putting in an appearance. There was an exchange of
views and information long before the Heads accomplished the
mundane and troublesome business of materialization. Thus it was
that the mists of Limbo now rumbled with thought, counter thought
and—on this particular occasion—downright aggravation, even before
the arrival of the Supreme Head in the vapored chambers. There was
an air of foreboding.
Having declined all vanities in the pursuit of the Ultimate Intelligence,
the Heads had allowed themselves to evolve into literal
representations of their titles. Directing all their energy and
development to the brain and its encasement, their bodies had
suffered proportionately so that now they were little more than a
group of preposterously large craniums, shaggy with cerebration,
bearing faces weighted with the ponderous woe of Life, Death,
Eternity and other such mental ballast. Five in all, they made up a
company to be avoided whatever the cost.

The Supreme Head cleared his throat and Eternity rattled with
phlegmy discontent. Baleful glances were exchanged all around.
"Well," said the Supreme Head, after a pause for attention. "I
suppose you all know the reason for this meeting by now?"
The Second Head, a bald party with large ears, nodded sadly. "You
say this blighted Pillsworth has gone and got himself shot this time?"
"Precisely," the Supreme Head affirmed. "In a broadcasting studio, if
you please. There's simply no keeping that man out of trouble."
"But why should we want to keep him out of trouble?" the Third
Head, an elongated customer with eye pouches, wanted to know.
"That's hardly our responsibility."
"There's George Pillsworth," the Supreme Head said fatefully. "Surely
you haven't forgotten about George?"
A hush fell over the Council, a hush of horror.
"Not George again?" the Second Head shuddered. "We don't have to
face him again, do we?" He looked around beseechingly at the
others. "After all, Pillsworth's only injured, isn't he? He's not dying?"
The Supreme Head looked for a moment as though he wished he had
shoulders so he might shrug them hopelessly. "The vibrations are
confused again," he sighed. "I don't know what the interference is
around Pillsworth, but the call never comes through clearly. All we
know is that he's gotten himself into another mess of some sort and
is either dead or dying."
"It seems that the subversives are still strongly active in the United
States, and of course Pillsworth couldn't stay out of it like a good
citizen. He was approached by some men delegated by government
authority to take control of national advertising. The theory was that
American advertising could be used as a strong combative
propaganda weapon against the enemy propaganda already
circulating through the country. A committee was delegated to secure
the cooperation of the nation's leading advertising agencies.
Naturally, since Pillsworth is the nation's leading advertising
executive, they contacted him first."
"Then Pillsworth is a subversive?" the First Head enquired. "That's
how he got into trouble?"
"Not at all," said the Supreme Head. "That's just it. Pillsworth wasn't
subversive, but the government committee was."
"Eh?"
"Exactly. It turned out that the program was one of the cleverest
propaganda schemes ever devised. Actually, their aim was to insert
alien ideals into the nation's advertising."
"But you said the plan had government approval."
"That's the really clever part of it. The method of presentation, while
seeming on the surface to denounce the foreign creed and uphold
the American one, actually was designed to win support for the
enemy. The sales psychology employed was of the negative."
"Negative?"
"That's correct. It's the old principle of telling people they don't want
a thing until they develop a feeling of defiance and decide they are
going to have it. It's an extremely subtle approach, but almost
infallible if properly developed. Knowing this, these men had a
perfect plan, so subtle that even the government didn't recognize it.
Also, they had help from within. A certain Congressman Entwerp
pushed through the legislation."
"But Pillsworth saw through it?"
"Instantly," the Supreme Head nodded. "It was a principle he had
been using assiduously for years, in fact the very one through which
he achieved his success. The whole plot was as clear as a May morn
the moment he heard it. That's when the trouble started. He
contacted Congressman Entwerp."
"Oh, dear!"
"Indeed. Entwerp responded by holding Pillsworth up to ridicule."
"But Pillsworth had logic on his side."
The Supreme Head smiled tolerantly. "That's the Earth for you every
time," he said. "Show a human a bit of logic and he gets truculent on
the spot. Pillsworth was denounced as a witch hunter and instructed
under penalty of law to cooperate to the fullest."
"Shocking," the Third Head said. "I begin to feel sorry for this
Pillsworth."
"Pillsworth was similarly shocked. But he didn't feel sorry for himself.
Despite his inclination for the quiet conservative life, he fought back."
"Good," the Fourth Head put in. "I'm glad; it gives the story zip."
"My thought in telling you this," the Supreme Head said caustically,
"is merely to inform, not entertain."
"Sorry, sir."
The Head nodded acknowledgment. "But to get on, Pillsworth
presented his case to a news broadcaster and asked to be allowed to
recite his story to the nation in the interests of national security. He
was shot. By whom we do not know; the fellow got away. But the
fact we must hold in mind is that he definitely was shot."
"Then it really is serious," the Third Head said. "We may have to
interview this deadly George after all."
"It's unavoidable," the Supreme Head sighed. "There's no way
around it."
"But we're not positive Pillsworth is dead yet. Couldn't we wait and
be sure?"
"His vibrations have been broken," the Supreme Head said. "Actually
we have no cause to hesitate." He sighed. "I suppose we might as
well get it over with."
The others nodded in reluctant agreement. There was an oppressive
silence.
"But didn't we banish George?" the First Head said. "We must have
after his last excursion to Earth."
"That's right," the Second Head agreed. "I remember distinctly. He
attempted to fire poor Pillsworth off into outer space without a
pressure suit. We banished him to the Void to sing bass in the
Moaning Chorus."
"We certainly picked the right party for the job," the First Head
reflected. "There isn't a more base spirit in all Limbo. Has he been
summoned?"

The Supreme Head coughed regretfully. "I issued the call through
Message Center before I announced the council."
"Oh, dear," the First Head murmured, "then the stinker is practically
on the sloop at this very moment."
"The stinker is crossing the sloop even now," the Supreme Head
amended, his gaze fastened hauntedly on a disturbance in the outer
mists. "Here he comes."
"Secure your valuables," the Second Head said morosely. "And keep
your hands in your pockets."
Hesitantly, under the unblinking disapproval of the Council, George
materialized. As the Council watched, a duplicate of Marc Pillsworth's
long, lean body, made vague by misted robes, rose solidly out of the
moiling vapors. It grew to full stature, rounded out at the shoulders,
extended a neck, then stopped short of the head. There was an
expectant pause, but nothing further developed.
"The rotter's ashamed to face us," the First Head observed sourly.
"Little wonder," the Third Head muttered. "After the way he's blotted
the haunting profession, he hasn't got a leg to stand on."
"George Pillsworth," the Supreme Head intoned with exasperation,
"spiritual projection of the mortal entity, Marc Pillsworth, approach
the Council. And put on your head, you fool."
George stirred, and his head, working from the chin upward,
materialized, revealing the face of Marc Pillsworth. All in all, as faces
go, Marc's—and consequently also George's—hit very close to
average. It was a nice face, a pleasant face, for all its lack of
distinction. On George, therefore, it was a misleading face. With its
lean plainness, its serious grey eyes and its shock of sandy hair, it
failed utterly to express even a whit of George's unprincipled
temperament.
"Is that better, sir?" George asked, edging warily forward.
"Hardly that," the Supreme Head groused. "The less of you the
better. However it helps us somewhat to get a clue to the inner
festerings of that depraved mind of yours." He gazed at George for a
long, reflective moment, then made a sad, clucking sound. "I simply
cannot imagine what Marcus Pillsworth must have thought when he
discovered that his spiritual entity was a tacky, ebony-hearted,
feather-headed wretch like you. Why aren't you more like your mortal
source?"
George shrugged sheepishly. "I guess I'm just no damn good," he
murmured.
"You flatter yourself," the Supreme Head said. "You're much worse
than no damn good. You're simply awful. I wonder if Limbo will ever
live you down."
"I hope so, sir," George said contritely.
"Nevertheless," the Supreme Head went on, "much as I loathe it, I
suppose we must get on with it. I suppose you know why you've
been summoned?"
George nodded dimly. "They reported me for teaching the Moaning
Chorus to syncopate."
"What!" the Supreme Head gasped. "You did what?"

George looked up, afrighted; he'd given himself away again with no
need. "Yes, sir," he sighed resignedly, "I thought that if we got up a
good hot act we might be able to wangle a few guest shots with the
Celestial Choir. Actually, we've worked out a really sock arrangement
of the Wham Bam Blues. I'm sure that if you heard it...."
"No!" the Supreme Head roared. "You couldn't! Of all the
unmitigated...!" He stopped and waited for his spleen to subside.
"George Pillsworth," he said, "you are insufferable."
"I suppose so, sir," George said. "However my intentions...."
"Blast your intentions!"
"Yes, sir. I'm very sorry."
"Never mind. In that case it's probably just as well that things are as
they are. It'll be a great relief to be rid of you."
"Rid of me?" George said fearfully. "You aren't going to...?"
"Unfortunately, no," the Supreme Head sighed. "What I mean is that
your mortal part, Marc Pillsworth, has got himself shot."
George looked up sharply. His whole aspect changed; his eye
brightened; his entire being grew more alert. "I'm to be sent to Earth
as a permanent haunt? Oh, sir...!"
"Hold it!" the Supreme Head snapped. "Don't go into a spring dance.
There's a hitch."
"Oh," George said, but his eagerness was not noticeably dampened.
To George, the merest prospect of a visit to Earth was only to be
regarded with rapturous anticipation. To him that distant world of
mortals was a place of boundless and exquisite attraction. It was
made up in equal parts of liquor, women and larceny and anything
else that existed there was merely the result of these things brought
together in odd combination. For George, Earth was absolutely the
last gasp.
Of course George had never achieved the ultimate accomplishment of
establishing permanent residence on Earth, for on all of his previous
visits he had arrived only to find that Marc was still alive and that he
could not legitimately remain. If on these occasions, George had
done his level best to rectify this error with whatever murderous
means at hand, it did not imply that the ghost held any personal
animosity for Marc. It was simply that George's was the sort of
temperament which boggled at almost nothing to achieve its end.
"What's the catch?" he asked.
"Don't be flip," the Supreme Head admonished. "And stop
syncopating."
"Syncopating?" George asked innocently. "I'm standing perfectly still."
"It's your mind," the Supreme Head said. "It's jogging about like a
cat on hot bricks. It shows all over you. This is an occasion of
enormous seriousness."

George did his best to assume an expression of profound sobriety.


"Yes, sir," he murmured.
"First of all," the Supreme Head continued, "as usual there is some
question as to Pillsworth's actual status. He has been shot, it's true,
and his vibrations are definitely broken. However, experience has
taught us to be wary in the case of Pillsworth. Often we have acted
on false alarms in the past and have been sorry." The Head paused
and beetled his brow. "Of course we need not have regretted those
errors had you behaved yourself at all in the manner of a decent,
self-respecting shade. Nevertheless, we don't dare take a chance
despite our reluctance in the matter. Pillsworth's wound falls into the
mortality class, so we have no alternative but to issue you your travel
orders and the usual allotment of ectoplasm." He fixed George with
an unhappy stare. "And get that look of evil delight off your face."
"Sorry, sir," George said.
"And make up your mind right now that this is a business trip. If
Pillsworth is not dead or definitely dying when you arrive you will
return instantly. Do you understand?"
"Yes, sir."
"And if he isn't dead or dying you will do nothing to alter this state of
affairs. You will not undertake on your own initiative to shove him off
tall buildings, under moving trucks or into open manholes. You will
not threaten him with ropes, guns, explosives, rare poisons or knives,
or attempt to dispatch him to heaven by means of rocket. Have you
got all that straight?"
"Yes, sir," George said quietly. "Hands off. I understand."
"I hope you do," the Head said ominously, "for your own sake.
Anyway, I suppose you'd better go along now and start checking out
through Supply. All that's left here is for you to raise your right hand
and swear by memory to the Ten Commandments of the Hunter's
code. However, I suppose you've got them all cribbed on the sleeve
of your robe."
George lowered his gaze. "Yes, sir," he murmured. "I have."
"Then skip it," the Head sighed resignedly. "Just clear out."
"Yes, sir," George said, brightening. "Thank you, sir."
As the mists swirled up around George, and he gradually dissolved
into their vaporish currents, a joyous grin lighted his face....
Three sets of eyes fastened clinically on the X-ray with worried,
professional interest.
"There's a slight chance," the first doctor said, "if we operate
immediately."
"Too slight," the second murmured. "The bullet's too close to the
heart. He'll die on the table."
"He'll die anyway. We're merely taking the only chance there is."
"I suppose so. Has his wife arrived yet?"
"She's with him now."
"He's not conscious, is he?"
"No, certainly not, but they could not keep her away."
"We'd better explain how it is. We're almost certain to lose him."
"I suppose so."
There was a pause before they turned and reluctantly left the room.
Outside, in the hospital corridor, the first doctor proceeded to the
door at the end of the hall while the other two stayed behind. He
opened the door and quietly stepped inside.
Marc lay still on the bed, his pleasant face drawn and pale against the
pillow. Julie sat beside the bed, a classic figure of silent grief, her
blonde beauty drained with uncomprehending fright. She did not cry.
Nor did she move as the doctor walked toward her from the door.
"Mrs. Pillsworth ..." the doctor said, but Julie remained motionless.
He moved closer to her and placed his hand gently on her shoulder.
"We've just seen the X-ray." At this Julie looked up. "We'll have to
operate instantly. The preparations are being made now." He paused.
"The chances for success are negligible."
Julie nodded dazedly. "I know," she whispered. "I know...."
She did not resist as the doctor took her arm and guided her to the
door. At the last moment, though, she paused and looked back at the
lean face on the pillow.
"He looks so peaceful," she said. "He looks so content. Does a dying
man ever dream, doctor?"

Even Marc himself could not have fitted a positive answer to Julie's
question. Did he dream? Or had he merely retreated from the world
to a realm of absolute reality? He didn't know himself.
He remembered passing through caverns of roaring darkness, only to
be caught up by a tongue of searing flame and hurled into some
obscure dimness where it seemed that all the thought, melody, all the
remembered sensation of a lifetime writhed about him like vague
forms, one interposed upon the other, in unpatterned confusion.
But now these entangled vagaries faded away and suddenly he found
himself sitting on a green slope at the outer perimeter of a grove of
graceful trees. A blue mist drifted lightly up the far rise to soften the
horizon. Marc was no stranger to this place for he had visited it often.
He felt no dismay at finding himself again in the valley of his own
mind. Indeed, through the last few years, it had become as familiar
to him as his own home or office. So had the redheaded minx who
found her existence there.
Marc stirred and looked around. The landscape was uninhabited. No
lovely, lightly clad figure appeared on the horizon, no lithe form
emerged from the groves and ran toward him.
Marc frowned anew over the improbable fact of Toffee. Certainly she
existed in his mind, a constant and consistent product of his
imagination. That was perfectly easy to understand. The parts of it,
though, that he never quite got used to were her periods of existence
outside his mind, in the world of actuality.
What Marc had never been able to really comprehend was that his
mind could project into the physical world a physical being—to such
an extent that her existence was not only apparent to himself but
also to everyone else who came within the radius of the mental
vibration which produced the girl.
The question in Marc's mind, then, was whether Toffee really existed,
was truly real, or whether she was merely an hallucination, a sort of
contagious hysteria.
Toffee's personality always got in the way of the answer. The girl was
infinitely distracting, from the pert aliveness of her quick green eyes
to the full redness of her lips. Beyond that there was the almost
shameful perfection of her supple young body. These things blocked
analytical thought. Then, too, there was her unerring instinct for
roaring, bounding madness, and her absolute contempt for the
logical, the moral or the conservative. Toffee, in brief, was at once
brash, embarrassing, impetuous, warm, high-handed, endearing,
maddening and completely unforgettable. So to all practical purposes,
then, she was real; the matter of Toffee's source was pallidly
unimportant next to the vivid fact of Toffee herself.
Marc stretched luxuriously and got to his feet, but as he did so he
peered around toward the green obscurity of the forest. There was
still no movement, no sound. He frowned quizzically. This wasn't at
all usual. Always before Toffee had been there to greet him almost at
the instant of his arrival. Another time she would be swarming all
over him by now.

He shrugged and started aimlessly up the rise. At first he climbed


unhurriedly, but as he drew nearer the trees his gait quickened. At
the outskirts of the forest he found himself pausing to listen, but
there was no sound. The feathery branches swayed in silent grace
before him. A small concern began to trickle into his mind.
The blue mists broke smoothly before his stride as he entered the
cool enclosure of the forest. Again he paused.
"Toffee...?" he found himself calling.
There was no answer.
He shoved ahead, and now there was a sort of anxiety in his step,
and he took care not to break the stillness lest Toffee answer. An odd
feeling of bereavement came over him, though he told himself it was
foolish. After all, the girl was entirely imaginary, and a pack of trouble
into the bargain. Then suddenly he stopped.
An odd murmuring seemed to come from the left. He moved in that
direction, stopped to listen, then hurried on. Ahead he saw a dim
lightness sketched through the trees, a suggestion of a clearing
obscured by the dense branches. He approached it, parted the foliage
and looked out. He stopped short.
Toffee sat in the middle of the clearing, her legs folded under her. Her
eyes were closed and one slender hand was pressed to her forehead
in an attitude of labored concentration. Her slight tunic, an emerald
transparency at best, did little to conceal the impertinent perfection
of her figure. She was leaning forward just a bit, and her flaming hair
hung loose over her shoulders. She seemed to be chanting
something to herself, though Marc couldn't make it out.
"Toffee...?" he said, and stepped forward to brace himself against the
inevitable rush of brash affection.
The girl opened her eyes and looked around hastily.
"Sit down somewhere," she said, "and be quiet."
"Huh?" Marc asked.
Toffee didn't answer. Instead, she closed her eyes, swayed back
lightly on her shapely haunches and began the muttered chant anew.
Marc swayed a trifle himself, with astonishment—and perhaps a tinge
of disappointment. This wasn't like Toffee at all, not by a long shot.
He moved slowly to her side and gazed down at her intent, upturned
face.
"Toffee...?" he hazarded.
She didn't open her eyes. Her lips moved. "Molecules," she said.
"What?" Marc asked.
"Molecules," Toffee repeated. "Molecules ... molecules...."
"Molecules?" Marc said. "What are you talking about?"
Toffee opened her eyes at this and looked up at him with anxious
irritation.
"Please be still," she said. "I've got to think about molecules
exclusively. It isn't helping any, your gabbing away in my ear."
"But why?" Marc asked. "What about molecules?"
"Everything depends on them, that's all," Toffee said impatiently.
"Now, just...."
"But wait a min—!"
"Quiet," Toffee said. "Don't you realize that you're tottering on the
brink of death at this very moment? Me, too, for that matter."
"Death?" Marc asked. "What are you talking about?"

Toffee looked at him aghast. "Don't you remember?" she asked.


"Have you actually forgotten about being shot in the studio?"
Marc stared down at her in growing horror. A small, agonized
memory screamed out of the dark inner shadows of his awareness.
"Oh, Lord!" he cried. "I'm dying!"
"And if those licensed butchers get to hacking you up, you're a
goner," Toffee said anxiously. "I have the inside information. There
isn't much time. I've got to concentrate like wild."
"But...!"
"Quiet!" Toffee broke in. "Please be quiet," she closed her eyes again
and her lips began to move as before. "Molecules," she murmured.
Marc remained rigid at her side. Panic rose inside him and filled his
throat. His impulse was to turn and run blindly—perhaps back to that
dying mortal body—but his terror held him transfixed. Staring down
at Toffee, he felt he might go mad in the next moment. In the next
moment he was certain he had.
Just in front of Toffee, close to the mossy greenness, he caught sight
of a quick flicker of light, a strange disembodied illumination that was
at once its own source and product. As he watched it flickered again,
grew brighter and became a steady radiance. He glanced back at
Toffee, but her face had become fixed and masklike. Her lips no
longer moved.
The radiance grew swiftly, to an almost unbearable brightness. In it
there was a cold hard suggestion of metal. Then it began to take
form and solidify. Marc blinked as the thing, whatever it was, grew
slowly out of the gleaming brilliance.
First a cylinder emerged, about a foot long and four or five inches in
diameter. For a moment the object seemed to have completed itself,
but then, one at either end, a pair of funnel-shaped openings
emerged. These completed, a small, two-way switch arrangement
appeared at the top and in the center of the cylinder. After that, the
radiance was gone and only the strange instrument remained, lying
on the grass before Toffee as though cast there by a careless hand.
"What—!" Marc gasped.
Toffee's perky features relaxed. She opened her eyes.
"Did it turn out all right?" she asked brightly. "Is it finished?"
"Huh?" Marc asked. He pointed. "You mean that?"
"Oh, wonderful!" Toffee cried, delighted. "It's rather pretty the way it
shines, isn't it?"
"What is it?"
"How should I know?" Toffee said blandly. "Just a gadget. There's
never been one before."
"You mean you just developed it out of your mind?"
"Sure," Toffee said. "It's a thought product—like me. Now if it only
works right...." Picking up the instrument, she looked at it carefully
and nodded with satisfaction. "It should be simple to operate."
"But what's it for?"
"I'll show you," Toffee said. She pointed to a nearby tree. "See that?"
Marc nodded. "Keep looking at it."

Turning to the tree, she held the cylinder toward it, so that one of the
funnels was aimed squarely in its direction.
"Now watch," she said, and pressed the switch.
Marc, staring at the tree in rapt attention, started with surprise.
Suddenly the tree was gone with no sign that it had ever been there.
"What...!"
"The next part is more important," Toffee said.
"Next part?" Marc said dazedly. "But where is it? Where...?"
"See there?" Toffee said, and this time she pointed to the center of
the clearing. "Watch."
Holding the cylinder so that the opposite end was pointed to the
clearing, she pressed the switch in the other direction. Instantly the
tree shot into being exactly at the spot she had indicated.
Marc stared. It was the same tree—the one that had disappeared—
and yet it was subtly different. It seemed greener now, more alive.
"What happened?" he asked. "What did you do to it?"
"Molecules," Toffee said, smiling. "I broke it down into molecules,
then projected it again. The machine absorbed the tree in molecules,
compressed them, reconstructed the faulty or destroyed ones,
eliminated all harmful matter and retained the count to reestablish it
in perfect balance and health. It worked fine."
"My gosh!" Marc said.
Drawing close to him, Toffee twined her arms around his neck with
knowing deliberation and drew his surprised face down close to hers.
"I'm going to save your stodgy life with molecules, you skinny old,
care-worn wraith," she breathed. "Then you'll be in my pay for the
rest of your days. Just keep it in mind later when things begin to
happen."
"Huh?" Marc said. "What things?"
"You'll see," Toffee said. "Wow!"
Marc drew himself up stiffly. "Now, look here," he said sternly, "you
can just get this wow business right out of your head...."
"And if that doesn't work," Toffee said, "I've been studying
hypnotism. I can transfix a snake at fifty yards." She brushed her
cheek lightly against his. "Just think of that, you scaly old reptile."
"Just a second," Marc said. "If you think for one sec—"
But the sentiment was lost as Toffee renewed her hold on his neck
and kissed him warmly and at considerable length on the mouth.
"That," she whispered, "is just a token payment in advance. Just wait
till the mortgage comes due!"
TOFFEE

"Why, you little hussy...!" Marc wheezed. "You haven't the moral
sense of a brickbat!"
He stopped short, for suddenly the forest had begun to darken and a
sharp wind came alive in the trees. He glanced around, startled, as
the earth began to tremble beneath them. Instinctively, he whirled
about, looking for an escape from the forest, but suddenly, with a
groan of dismay, the world went black, and he was only aware of
Toffee's arms closing tight about his neck....

The orderly was a pale, antiseptic type. And he was resentful.


Wheeling Marc along the hallway toward Surgery, he looked down at
the drawn face beneath him with a twinge of pique. He strongly
resented the fact that the face was not behaving at all as the face of
a true corpse-elect should.
According to the orderly, a dying man had no right to twitch and
flutter his eyelids the way this one was doing, let alone showing signs
of coming completely to life. It made the orderly nervous and upset.

MARC PILLSWORTH

For a moment the orderly almost succumbed to an impulse to walk


off and leave the patient to shift for himself. It was what he deserved
if he was going to act that way. Nonetheless, he remained.
Consequently, Marc's first vision, upon returning to consciousness,
was of a pale, fretful face with white eyelashes and thin lips. He had
expected something better.
"Who are you?" he asked weakly. "Are you the doctor?"
The orderly shook his head sullenly. "I'm the orderly. The doctor's
waiting."
"They mustn't operate," Marc murmured. "I'll die...." He stopped as a
pert face suddenly blurred into view just behind that of the orderly. A
slender hand brushed back a wayward lock of red hair. Toffee smiled
and winked.
Marc moaned. "Oh, so it's you, is it?" he sighed. "What are you so
happy about? I feel awful."
"I'm not happy, sir," the orderly said, mystified. "I'm not happy at all.
In fact, if you want the truth...." He paused, and the apprehensive
expression of one who detects an unseen presence behind him
overtook his face. Very slowly, he turned around.
It would be difficult to say what the orderly expected to find behind
him: a fanged reptile might have made a good guess, a slavering
fiend another. It is certain, however, judging from his reaction, that
on the list of things he did not expect to find, a scantily clad redhead
was number one. Toffee, her legs crossed to perfection, the cylinder-
like gadget under her arm, sat jauntily on the edge of the cart,
smiling a bright greeting. The young man leaped backwards and
froze in a transfix of amazement.
"Auk!" he exclaimed.
Toffee turned to Marc. "Is he doing a bird imitation?" she asked.
"Should I applaud?"
"Don't be funny," Marc said feebly. "I feel terrible."
"I know," Toffee said. "I got here just in time."
"For what?" Marc asked apprehensively. "What are you going to do?"
Toffee patted the cylinder. "I'm going to save your life," she said.
"Don't you remember?"
Marc looked at her through heavy lids. "That's silly," he murmured.
"Just go 'way and let me die in peace."
Unmindful, Toffee leaped lightly to the floor, stood back and aimed
the gadget at Marc. "All set?" she said.
"Here!" the attendant said, suddenly recovering the faculty of speech.
"What are you doing?"
"Advancing medical science a mile a minute," Toffee said. "Don't
interrupt."
"But...!"

Toffee placed her hand menacingly on her hip and fixed the young
man with a steely eye. "Am I going to have to deal with you?" she
asked, "Or are you going to button your lip like a good child?"
The orderly spoke no further.
Toffee raised the cylinder, sighting the length of Marc's lean, sheet-
covered body. Then she pressed the switch.
The orderly stared, wide-eyed, and repeated his bird imitation. The
place where Marc had lain was suddenly as bare as a banquet board
after the feast. Where a moment before there had been a long thin
man, now there was only a long, thin sheet.
"Hey!" the orderly bleated. "Ho!"
"So long, phrasemaker," Toffee said, and tucking the cylinder under
her arm, moved off quickly down the hall and around the corner.
It was just as the orderly observed the last flirt of Toffee's hip that
the doctor appeared from the door of the operating room and looked
distractedly in his direction.
"Good grief, man!" he said, "haven't you brought Pillsworth with
you?"
The orderly started nervously and looked around.
"He ... he ... he...!" he gibbered. "That is, she ... she...!" He pointed
in hopeless confusion down the hall.
"What are you babbling about?" the doctor enquired shortly. "Where
is Pillsworth?"
"He.... He's gone, sir!" the attendant blurted.
"Gone?" the doctor said. "Where did he go?"
The orderly looked away down the hall. "There was this girl, see ...
she had red hair and a can...."
"Now, just a minute, orderly," the doctor said measuredly. "If you
think you can distract me with the depressing details of your sex
life...."
"But you don't understand! She was holding this thing ... and she told
me to shut up ... and then Mr. Pillsworth wasn't there any more.
That's the truth!"
"Let me impress it upon you," the doctor said, "that this is a very
serious incident. I can't imagine how a half-dead patient managed to
get away from you, but you'll find him instantly and deliver him to
surgery if you know what's good for you. Meanwhile, I'll have the
alarm sent out to all the wards and offices. I hope you realize that
your carelessness has undoubtedly cost the patient his last chance
for life. Without the slightest doubt I can pronounce Marc Pillsworth
dead right now."
As the doctor spoke these last words, a small gust of wind—or at
least what could easily have passed for a small gust of wind—eddied
around the corner at the end of the hall. It was this slight disturbance
which marked the arrival of George on Earth.
At the sound of the doctor's voice, the ghost stopped, listened, then
clasped his hands together in a transport of joy. He had arrived just
in time to receive the happy news! Marc was dead and he, George,
had at last secured his permanent residency on Earth. Out of sheer
exuberance the delighted spectre let out a little moan of delight.
The orderly, who was watching the doctor gloomily out of sight,
turned sharply.
"Mr. Pillsworth?" he quavered thinly. "Mr. Pillsworth, please...?"

You might also like