Dive Into Python 1st Edition Mark Pilgrim
(Auth.) install download
https://ebookname.com/product/dive-into-python-1st-edition-mark-
pilgrim-auth/
Get the full ebook with Bonus Features for a Better Reading Experience on ebookname.com
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
Developing with PDF Dive into the Portable Document
Format 1st Edition Leonard Rosenthol
https://ebookname.com/product/developing-with-pdf-dive-into-the-
portable-document-format-1st-edition-leonard-rosenthol/
Dive into Close Reading Strategies for Your 3 5
Classroom 1st Edition Diane Lapp
https://ebookname.com/product/dive-into-close-reading-strategies-
for-your-3-5-classroom-1st-edition-diane-lapp/
Programming Python 4th Edition Mark Lutz
https://ebookname.com/product/programming-python-4th-edition-
mark-lutz/
Start Programming Using HTML CSS and JavaScript 1st
Edition Iztok Fajfar (Author)
https://ebookname.com/product/start-programming-using-html-css-
and-javascript-1st-edition-iztok-fajfar-author/
Youth Renewing the Countryside First Edition Renewing
The Countryside
https://ebookname.com/product/youth-renewing-the-countryside-
first-edition-renewing-the-countryside/
Down Syndrome Current Perspectives 1st Edition Richard
W. Newton
https://ebookname.com/product/down-syndrome-current-
perspectives-1st-edition-richard-w-newton/
Insect Symbiosis Volume 3 Contemporary Topics in
Entomology 1st Edition Kostas Bourtzis
https://ebookname.com/product/insect-symbiosis-
volume-3-contemporary-topics-in-entomology-1st-edition-kostas-
bourtzis/
Unleashing the Power of 3P The Key to Breakthrough
Improvement 1st Edition Dan Mcdonnell
https://ebookname.com/product/unleashing-the-power-of-3p-the-key-
to-breakthrough-improvement-1st-edition-dan-mcdonnell/
Encyclopedia of Governance 1° Edition Mark Bevir
(Editor)
https://ebookname.com/product/encyclopedia-of-
governance-1-edition-mark-bevir-editor/
Revelation X The Bob Apocryphon Hidden Teachings and
Deuterocanonical Texts of J R Bob Dobbs
https://ebookname.com/product/revelation-x-the-bob-apocryphon-
hidden-teachings-and-deuterocanonical-texts-of-j-r-bob-dobbs/
Praise for Dive Into Python:
"Whether you're an experienced programmer looking to get into
Python or grizzled Python veteran who remembers the days when
you had to import the string module, Dive Into Python is your 'desert
island' Python book."
-Joey deVilla, Slashdot contributor (www.slashdot.org)
'l1s a complete newbie to the language, I most certainly valued the
approach employed, and I constantly had those little thoughts like
'This is the way a programming language should be taught.'"
-Lasse Koskela, JavaRanch (www.javaranch.com)
"It [Dive Into Python] is a very impressive piece of work-it manages
to explain the Python language and, more importantly, the idioms
and customs ofPython programming, through a series of well-chosen
and interesting examples."
-Kevin Marks, Epeus' epigone {http://epeus.blogspot.com)
"It's not just on the technical side that the book scores high marks.
Mention must be made of the writing style, which is both accessible,
technically competent and riddled with peppery asides and wise
cracks. It works well, and it really is a pleasure to read. What's more,
the book succeeds in enthusing the reader. Highly recommended."
-(www.techbookreport.com)
"Dive Into Python is just what I needed to get started on becoming a
guru in the language."
-Blane Warrene (www.practicalapplications.net)
Dive Into Python
MARK PILGRIM
APress Media, LLC
Dive Into Python
Copyright © 2004 by Mark Pilgrim
Originally published by Apress in 2004
Permission is granted to copy, distribute and/ or modify this document under the terms of the
GNU Free Documentation Ucense, Version 1.1 or any later version published by the Free Software
Foundation; with no Invariant Sections, no Front-CoverTexts, and no Back-CoverTexts. A copy of
the license is included in the section Appendix B, entitled "GNU Free Documentation Ucense."
AII rights reserved. No part of this work may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information
storage or retrieval system, without the prior written permission of the copyright owner and the
publisher.
ISBN 978-1-59059-356-1 ISBN 978-1-4302-0700-9 (eBook)
DOI 10.1007/978-1-4302-0700-9
Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.
Lead Editor: Chris Mills
Technical Reviewer: Anna Ravenscroft
Editorial Board: Steve Anglin, Dan Appleman, Ewan Buckingham, Gary Cornell, Tony Davis,
Jason Gilmore, Jonathan Hassle, Chris Mills, Dominic Shakeshaft, Jim Sumser
Project Manager: Kylie Johnston
Copy Edit Manager: Nicole LeClerc
Copy Editor: Marilyn Smith
Production Manager: Karl Brooks
Production Editor: Katie Stence
Compositor: Kinetic Publishing Services, lLC
Proofreader: Unda Seifert
Indexer: Rebecca Plunkett
Cover Designer: Kurt Krames
Manufacturing Manager: Tom Debolski
The information in this book is distributed on an "as is" hasis, without warranty. Although every
precaution bas been taken in the preparation of this work, neither the author(s) nor Apress shall
have any liability to any person or entity with respect to any loss or damage caused or alleged to
be caused directly or indirectly by the information contained in this work.
For Ethan
Contents at a Glance
About the Author ................................................. xiii
Introduction ....................................................... xv
Chapter 1 Installing Python ................................... 1
Chapter 2 Your First Python Program ......................... 11
Chapter 3 Native Datatypes ................................... 23
Chapter 4 The Power of Introspection ........................ 49
Chapter 5 Objects and Object-Orientation .................... 71
Chapter 6 Exceptions and File Handling ...................... 97
Chapter 7 Regular Expressions ............................... 121
Chapter 8 HTML Processing .................................... 141
Chapter 9 XML Processing ..................................... 171
Chapter 10 Scripts and Streams ............................... 197
Chapter 11 HTTP Web Services ................................. 221
Chapter 12 SOAP Web Services ................................. 249
Chapter 13 Unit Testing ....................................... 271
Chapter 14 Test-First Programming ............................ 2B7
Chapter 15 Refactoring ........................................ 309
Chapter 16 Functional Programming ............................ 331
Chapter 17 Dynamic Functions ................................. 349
Chapter 18 Performance Tuning ................................ 367
Appendix A Python License ..................................... 387
Appendix B GNU Free Documentation License .................. 393
Index .............................................................. 401
v
Contents
About the Author ................................................. xiii
Introduction ....................................................... xv
Chapter 1 Installing Python ............................... 1
Which Python Is Right for You? ................................... 1
Python on Windows .................................................. 1
Python on Mac as X................................................. 3
Python on Mac as 9 ................................................. 6
Python on Red Hat Linux ............................................ 6
Python on Debian GNU/Linux ........................................ 7
Python Installation from Source .................................. 8
The Interactive Shell ............................................. 10
Summary ............................................................ . 10
Chapter 2 Your First Python Program ................... 11
Diving In .......................................................... 11
Declaring Functions ............................................... 12
Documenting Functions ............................................. 14
Everything Is an Object .......................................... 15
Indenting Code ..................................................... 18
Testing Modules: The if _name_ Trick ......................... 19
Summary ............................................................. 21
Chapter 3 Native Datatypes ............................... 23
Introducing Dictionaries ......................................... 23
Introducing Lists ................................................. 27
Introducing Tuples ................................................ 34
Declaring Variables ............................................... 36
Formatting Strings ................................................ 39
Mapping Lists ...................................................... 41
Joining Lists and Splitting Strings ............................ 43
Summary ............................................................. 46
vii
Contents
Chapter 4 The Power of Introspection ................. 49
Diving In .......................................................... 49
Using Optional and Named Arguments .............................. 51
Using type, str, dir, and Other Built-in Functions ........... 52
Getting Object References with getattr ......................... 56
Filtering Lists ................................................... 59
Understanding the Peculiar Nature of and and or ............... 61
Using lambda Functions ........................................... 64
Putting It All Together .......................................... 66
Summary ............................................................. 69
Chapter 5 Objects and Object-Orientation ............ 71
Diving In .......................................................... 71
Importing Modules Using from module import .................... 74
Defining Classes .................................................. 76
Instantiating Classes ............................................. 80
Exploring UserDict: A Wrapper Class ............................ 82
Using Special Class Methods ...................................... 86
Introducing Class Attributes ..................................... 91
Using Private Functions .......................................... 93
Summary ............................................................. 95
Chapter 6 Exceptions and File Handling ............... 97
Handling Exceptions ............................................... 97
Working with File Objects ....................................... 101
Iterating with for Loops ........................................ 106
Using sys. modules ................................................ 109
Working with Directories ........................................ 112
Putting It All Together ......................................... 117
Summary ............................................................ 118
Chapter 7 Regular Expressions .......................... 121
Diving In ......................................................... 121
Case Study: Street Addresses ................................... 121
Case Study: Roman Numerals ...................................... 124
Verbose Regular Expressions ..................................... 131
Case Study: Parsing Phone Numbers .............................. 133
Summary ............................................................ 139
viii
Contents
Chapter 8 HTML Processing ............................... 141
Diving In ......................................................... 141
Introducing Python's sgmllib. py ................................ 147
Extracting Data from HTML Documents ........................... 150
Understanding locals() and globals() .......................... 157
Using Dictionary-based String Formatting ...................... 161
Quoting Attribute Values ........................................ 163
Parsing HTML One Tag at a Time ................................. 165
Putting It All Together ......................................... 168
Summary ............................................................ 170
Chapter 9 XML Processing ................................. 171
Diving In ......................................................... 171
Importing Python Packages ....................................... 180
Parsing XML ....................................................... 182
Dealing with Unicode ............................................. 185
Searching for XML Elements ...................................... 191
Accessing XML Element Attributes ............................... 194
Summary ............................................................ 196
Chapter 10 Scripts and Streams .......................... 197
Abstracting Input Sources ....................................... 197
Using Standard Input, Output, and Error ....................... 202
Introducing Some XML Processing Techniques .................... 207
Handling Command-Line Arguments ................................ 212
Putting It All Together ......................................... 217
Summary ............................................................ 219
Chapter 11 HTTP Web Services ............................ 221
Diving In ......................................................... 221
How Not to Fetch Data Over HTTP ................................ 224
Supporting HTTP Features ........................................ 225
Debugging HTTP Web Services ..................................... 228
Setting the User-Agent .......................................... 229
Handling Last-Modified and ETag ................................ 232
Handling Redirects ............................................... 236
Handling Compressed Data ........................................ 241
Putting It All Together ......................................... 244
Summary ............................................................ 247
ix
Contents
Chapter 12 SOAP Web Services .............................. 249
Diving In ............................................................ 249
Installing the SOAP Libraries .................................... 251
Taking Your First Steps with SOAP ............................... 253
Introducing WSDL .................................................... 257
Searching Google .................................................... 261
Troubleshooting SOAP Web Services ............................... 265
Summary .............................................................. 270
Chapter 13 Unit Testing ..................................... 271
Diving In ............................................................ 271
Introducing the Test Suite ....................................... 272
Constructing Test Cases ........................................... 277
Summary .............................................................. 285
Chapter 14 Test-First Programming ....................... 287
Diving ~n (Stage 1) ................................................ 287
Converting Roman Numerals, Stage 2 .............................. 292
Converting Roman Numerals, Stage 3 .............................. 297
Converting Roman Numerals, Stage 4 .............................. 301
Converting Roman Numerals, Stage 5 .............................. 304
Summary .............................................................. 307
Chapter 15 Refactoring ...................................... 309
Diving In ............................................................ 309
Handling Changing Requirements ................................... 312
Refactoring for Performance ...................................... 321
Postscript ........................................................... 326
Summary .............................................................. 328
x
Contents
Chapter 16 Functional Programming ...................... 331
Diving In ......................................................... 331
Finding the Path ................................................. 333
Filtering Lists Revisited ....................................... 336
Mapping Lists Revisited ......................................... 338
Data-centric Programming ........................................ 340
Dynamically Importing Modules .................................. 341
Putting It All Together ......................................... 343
Summary ............................................................ 347
Chapter 17 Dynamic Functions ............................. 349
Diving In ......................................................... 349
Pluralizing Nouns J Stage 1 ...................................... 350
Pluralizing Nouns J Stage 2 ...................................... 353
Pluralizing Nouns J Stage 3 ...................................... 355
Pluralizing Nouns J Stage 4 ...................................... 356
Pluralizing Nouns J Stage 5 ...................................... 359
Pluralizing Nouns J Stage 6 ...................................... 361
Summary ............................................................ 365
Chapter 18 Performance Tuning ........................... 367
Diving In ......................................................... 367
Using the timeit Module ......................................... 370
Optimizing Regular Expressions ................................. 372
Optimizing Dictionary Lookups .................................. 376
Optimizing List Operations ...................................... 380
Optimizing String Manipulation ................................. 383
Summary ............................................................ 385
Appendix A Python License ................................. 387
A. History of the Software ...................................... 387
B. Terms and Conditions for Accessing or Otherwise
Using Python .................................................. 388
xi
Contents
Appendix B GNU Free Documentation License ........... 393
o. Preamble ....................................................... 393
1. Applicability and Definitions ............................... 393
2. Verbatim Copying .............................................. 395
3. Copying in Quantity .......................................... 395
4. Modifications ................................................. 396
5. Combining Documents .......................................... 398
6. Collections of Documents ..................................... 398
7. Aggregation with Independent Works ......................... 398
8. Translation ................................................... 399
9. Termination ................................................... 399
10. Future Revisions of This License .......................... 399
Addendum: How to Use This License for Your Documents ........ 400
Index ............................................................ 401
xii
About the Author
By DAY, MARK PILGRIM is an accessibility architect. By night, he is a husband and
father who lives in North Carolina with his wife, his son, and his dog. He would
like to thank his wife and his son, who have been exceedingly patient while he
worked on this book. The dog was not all that patient, but two out of three isn't
bad. Mark spends his copious free time sunbathing, skydiving, and reading
Immanuel Kant's The Critique of Pure Reason in the original Klingon.
xiii
Introduction
IF YOU ARE a developer interested in getting started quickly with the hottest
open-source language, this book is for you. Experience in other languages is
recommended but not required. If you have experience in Perl, Java, or Visual
Basic, the first few chapters will go even faster. Core programming structures
are shared among all languages, and this book contains many analogies to
help you become familiar with Python's syntax and move on to higher-level
concepts.
But even if you don't have a lot of experience with other modern pro-
gramming languages, this book is still a good place to start. It won't bore
you with long-winded treatises on the history of computer science. You'll
get down to business immediately and see how Python's interactive shell is
the perfect breeding ground for experimenting with programming concepts
before getting your feet wet with actual code.
This book is divided into a series of isolated case studies. Each chapter
focuses on a single piece of real code that does something meaningful and useful.
As each example brings up related issues, there are digressions to explore them,
but the discussion always comes back to the code in the end. This does not mean
that every chapter is an island. Many of the later chapters assume you have mas-
tered basic concepts covered in earlier chapters. These cases are clearly marked
in the text, with references and quick reviews to get you up and running quickly.
Here is an overview of what you'll find in this book:
Chapter 1, Installing Python: No matter what platform you're using,
Python runs on your computer. You'll step through how to install it on
Windows, Mac as x, Mac as 9, Red Hat Linux, and Debian GNU I Linux.
After downloading, you can be up and running and experimenting in
the Python interactive shell in five minutes.
Chapter 2, Your First Python Program: As promised, you'll dive into
your first complete Python program, odbchelper. py, and explore every line
of it in depth. This will show you how to declare functions, document your
code with the Python equivalent of JavaDoc, and test individual functions
from the Python interactive shell.
Chapter 3, Native Datatypes: Python has a rich set of native datatypes.
You'll learn how to manipulate lists, tuples, and dictionaries; how to
format strings; and how to use list comprehensions.
xv
Introduction
Chapter 4, The Power of Introspection: This chapter explores apihelper. py,
a short but powerful program that displays information about a module,
function, or class from the Python interactive shell. Diving into this pro-
gram will show you how to define functions with optional arguments, call
functions with named arguments, get references to Python objects with
the getattr() function, and use lambda to quickly define one-off functions.
Chapter 5, Objects and Object-Orientation: Python supports first-class
objects with a complete inheritance model. This chapter introduces a
class, Filelnfo, that encapsulates reading metadata from different types
of files. You'll see how to define classes and create instances of classes.
You'll also explore Python's powerful special class methods, which allow
you to define behavior in your custom classes that enables you to oper-
ate on them as if they were built-in datatypes. This chapter steps through
defining a class that behaves like a dictionary, but other special class
methods could allow classes to be added and subtracted like numbers,
or appended and sliced like lists.
Chapter 6, Exceptions and FOe Handing: Most modern programming
languages have some form of exception handling, and Python is no
exception. In this chapter, you'll see how Python's exception handling
works. Then you'll use it to safely work with files, directory listings, and
other external resources that can fail at any moment.
Chapter 7, Regular Expressions: This chapter introduces the concept of
regular expressions, which are a powerful pattern-matching technique. If
you have used Perl, this concept will be old hat, but few people use them
in other languages (even though all modern programming languages offer
regular expression libraries). This chapter steps through a series of mini-
studies to explore different forms of regular expression syntax to work
with street addresses, Roman numerals, and phone numbers.
Chapter 8, IITML Processing: One of Python's best-kept secrets is sgmllib,
a built-in library for dealing with HfML and similar forms of markup. This
chapter is centered around dialect. py, a program that takes HfML pages
and transforms the text into different dialects while leaving the HfML
markup intact. To understand this will require an in-depth look at Python's
sgmllib. There are also digressions to learn about dictionary-based string
formatting, and the localsO and globalsO functions for accessing all the
defined variables in the Python environment as a native data structure.
xvi
Introduction
Chapter 9, XML Processing: This chapter covers Python's built-in XML
processing libraries. You'll see kgp. py, a program that takes XML docu-
ments that define context-free grammars and parses them to generate
randomized output. This will take you through parsing XML documents,
accessing arbitrary elements and attributes within them, and recon-
structing XML files after they've been parsed. There is also a thorough
explanation of Unicode, which is central to XML text processing and is
also used within Python to store strings in multiple languages.
Chapter 10, Scripts and Streams: Another one of Python's strengths
is the concept of a me-like object, which allows you to get data from
multiple input sources the same way you would read from a file on disk.
This chapter's example is openanything. py, a utility library that lets you
handle an in-memory buffer as a file, the output of another running
process, or even a remote web page. There is also a discussion of han-
dling command-line arguments and flags in scripts that are run from
the command line.
Chapter 11, HTfPWeb Services: This chapter dives into HTTP with an
expanded version of the openanything.py module introduced in Chapter 10.
With HTTP web services, a proper implementation of HTTP is essential,
and this chapter will teach you the five features of HTTP you need to know:
setting the User-Agent, handling temporary and permanent redirects, tak-
ing advantage of the Last -Modified header, using Etags, and supporting
compressed data.
Chapter 12, SOAP Web Services: Python comes with a lot of libraries
(Python fans like to say that it comes with "batteries included"). However,
it doesn't yet come with a SOAP library, so the first step to using SOAP
web services is to install three libraries: PyXMl, fpconst, and SOAPpy. This
chapter steps you through that, and then dives into parsing WSDL files
and calling remote functions over SOAP. The chapter culminates in a
simple program that returns Google search results with the Google
SOAP API.
Chapter 13, Unit Testing: Unit testing is the idea that you should write
small, independent tests to check each of your functions. Python comes
with a unit testing framework, and this chapter will use the example of
validating Roman numerals to show you how to write unit tests in Python.
Chapter 14, Test-First Programming: Continuing where Chapter 13 left
off, this chapter will explore what it feels like to write code that already
has unit tests for it. When all your tests pass, stop coding.
xvii
Introduction
Chapter 15, Refactorlng: Continuing where Chapter 14 left off, this final
chapter on testing will show how to update your unit tests to handle
changing requirements, how to integrate new unit tests to cover newly
reported bugs, and how to refactor for performance without worrying
about breaking old code.
Chapter 16, Functional Programming: This chapter covers Python's
functional programming methods: map, filter, and lambda. Using a sam-
ple program to build and run regression test suites, you'll learn about
the joys of data-centric programming, dynamically importing modules,
and manipulating path information on the command line.
Chapter 17, Dynamic Functions: Python 2.3 introduces a new language
feature: generators. This chapter uses a staged approach to build the
same program in six different ways. By stage six, you'll see how genera-
tors can radic~y reduce your program's complexity, while actually
making it more flexible in the long run. Along the way, you'll learn about
string substitution with regular expressions, closures, and functions that
behave like first-class objects.
Chapter 18, Performance Tuning: Python is an interpreted scripting
language, but that doesn't mean you can ignore performance altogether.
This chapter explores some common mistakes that can make your pro-
gram run up to ten times slower than it could. You'll learn how to use
the built-in timeit module to optimize regular expressions, dictionary
lookups, list operations, and string manipulation.
I hope this book makes you love Python as much as I do. Let's dive in.
xviii
CHAPTER 1
Installing Python
WELCOME TO PYTHON. Let's dive in. In this chapter, you'll install the version of
Python that's right for you.
Which Python Is Right for You?
The first thing you need to do with Python is install it. Or do you? If you're using an
account on a hosted server, your ISP may have already installed Python. Most pop-
ular Linux distributions come with Python in the default installation. Mac OS X 10.2
and later versions come with a command-line version of Python, although you'll
probably want to install a version that includes a more Mac-like graphical interface.
Windows does not come with any version of Python, but don't despair! There
are several ways to point-and-click your way to Python on Windows.
As you can see already, Python runs on many operating systems. The full list
includes Windows, Mac OS, Mac OS X, and all varieties of free UNIX-compatible
systems like Linux. There are also versions that run on Sun Solaris, AS/400, Amiga,
OS/2, BeOS, and a plethora of other platforms you've probably never even heard of.
What's more, Python programs written on one platform can, with a little care,
run on any supported platform. For instance, I regularly develop Python programs
on Wmdows and later deploy them on Linux.
So back to the question that started this section, "Which Python is right for
you?" The answer is whichever one runs on the computer you already have.
Python on Windows
On Windows, you have a couple choices for installing Python.
ActiveState makes a Windows installer for Python called ActivePython,
which includes a complete version of Python, an IDE with a Python-aware code
editor, plus some Windows extensions for Python that allow complete access to
Windows-specific services, APls, and the Windows Registry.
ActivePython is freely downloadable, although it is not open source. It is the
IDE I used to learn Python, and I recommend you try it unless you have a specific
reason not to use it. One such reason might be that ActiveState is generally several
months behind in updating the ActivePython installer when new versions of Python
1
Chapter 1
are released. If you absolutely need the latest version of Python, and ActivePython is
still a version behind as you read this, you'll want to use the second option for
installing Python on Wmdows.
The second option is the "official" Python installer, distributed by the people
who develop Python itself. It is freely downloadable and open source, and it is
always current with the latest version of Python.
Option 1: Installing ActivePython
Here is the procedure for installing ActivePython:
1. Download ActivePython from
http://www.activestate.com/Products/ActivePython/.
2. If you are using Windows 95, Windows 98, or Windows Me, you will
also need to download and install Windows Installer 2.0, from http: I I
download.microsoft.com/download/WindowsInstaller/Insta11/2.0/W9XMel
EN-US/InstMsiA.exe, before installing ActivePython.
3. Double-click the installer, ActivePython-2.2.2-224-win32-ix86.msi.
4. Step through the installer program.
5. If space is tight, you can do a custom installation and deselect the docu-
mentation, but I don't recommend this unless you absolutely can't spare
the 14MB.
After the installation is complete, close the installer and choose Start ~
Programs ~ ActiveState ActivePython 2.2 ~ PythonWin IDE. You'll see the
following:
PythonWin 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) -
see 'Help/About PythonWin' for further copyright information.
»>
Option 2: Installing Python from Python.org
Here is the procedure for installing Python from http://www.python.org/:
2
Installing Python
1. Download the latest Python Windows installer by going to
http://www. python. org/ftp/python/ and selecting the highest version
number listed, and then downloading the . exe installer.
2. Double-click the installer, Python- 2. xxx. yyy. exe. (The name will depend
on the version of Python available when you read this; at time of writing,
the latest version was Python 2.3.3.)
3. Step through the installer program.
4. If disk space is tight, you can deselect the HTML Help file, the utility
scripts (Tools/), and/or the test suite (Lib/test/).
5. If you do not have administrative rights on your machine, you can select
Advanced Options, and then choose Non-Admin Install. This just affects
where Registry entries and Start menu shortcuts are created.
After the installation is complete, close the installer and select Start ~
Programs ~ Python 2.3 ~ IDLE (Python GUI). You'll see the following:
Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32
Type "copyright", "credits" or "licenseO" for more information.
****************************************************************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
****************************************************************
IDLE 1.0
»>
Python on Mac OS X
On Mac as X. you have two choices for installing Python: install it or don't install
it. You probably want to install it.
Mac as x 10.2 and later comes with a command-line version of Python pre-
installed. If you are comfortable with the command line, you can use this version
for the first third of the book. However, the preinstalled version does not come
3
Chapter 1
with an XML parser, so when you get to the XML chapter, you'll need to install
the full version.
Rather than using the preinstalled version, you'll probably want to install the
latest version, which also comes with a graphical interactive shell.
Running the Preins tailed Version of Python on Mac OS X
To use the preinstalled version of Python, follow these steps:
1. Open the 1Applications folder.
2. Open the Utilities folder.
3. Double-click Terminal to open a terminal window and get to a com-
mandline.
4. 'JYpe python at the command prompt.
Try it out:
Welcome to Darwin!
[localhost:~] you% python
Python 2.2 (#1, 07/14/02, 23:25:09)
[GCC Apple cpp-precomp 6.14] on darwin
Type "help", "copyright", "credits", or "license" for more information.
»> [press Ctrl+D to get back to the command prompt]
[localhost:~] you%
Installing the Latest Version of Python on Mac OS X
Follow these steps to download and install the latest version of Python:
1. Download the MacPython-OSX disk image from
http://homepages.cwi.nl/-jack/macpython/download.html.
2. If your browser has not already done so, double-click
MacPython-OSX - 2.3 -1. dmg to mount the disk image on your desktop.
3. Double-click the installer, Macpython-OSX.pkg.
4. The installer will prompt you for your administrative username and
password.
4
Installing Python
5. Step through the installer program.
6. After installation is complete, close the installer and open the
/ Applications folder.
7. Open the MacPython-2.3 folder.
8. Double-click PythonIDE to launch Python.
The MacPython IDE should display a splash screen, and then take you to the
interactive shell. If the interactive shell does not appear, select Wmdow ~ Python
Interactive (or press Command-O). The opening screen will show the following
information:
Python 2.3 (#2, Jul 30 2003, 11:45:28)
[GCC 3.1 20020420 (prerelease)]
Type "copyright", "credits" or "license" for more information.
MacPython IDE 1.0.1
»>
Note that once you install the latest version, the preinstalled version is still
present. If you are running scripts from the command line, you need to be aware
of which version of Python you are using, which you can check as shown in
listing 1-1.
Listing 1-1. Two Versions of Python
[localhost:-] you% python
Python 2.2 (#1, 07/14/02, 23:25:09)
[GCC Apple cpp-precomp 6.14] on darwin
Type "help", "copyright", "credits", or "license" for more information.
»> [press Ctrl+D to get back to the command prompt]
[localhost:-] you% /usr/local/bin/python
Python 2.3 (#2, Jul 30 2003, 11:45:28)
[GCC 3.1 20020420 (prerelease)] on darwin
Type "help", "copyright", "credits", or "license" for more information.
»> [press Ctrl+D to get back to the command prompt]
[localhost:-] you%
5
Chapter 1
Python on Mac OS 9
Mac OS 9 does not come with any version of Python, but installation is very simple,
and there is only one choice.
Follow these steps to install Python on Mac OS 9:
1. Download the MacPython23full.bin file from
http://homepages.cwi.n1/-jack/macpython/down1oad.htm1.
2. If your browser does not decompress the file automatically, double-click
MacPython23full. bin to decompress the file with Stuffit Expander.
3. Double-click the installer, MacPython23fu11.
4. Step through the installer program.
5. After installation is complete, close the installer and open the
I Applications folder.
6. Open the MacPython-OS9 2.3 folder.
7. Double-click Python IDE to launch Python.
The MacPython IDE should display a splash screen, and then take you to the
interactive shell. If the interactive shell does not appear, select Wmdow ~ Python
Interactive (or press Command-O). You'll see the following:
Python 2.3 (#2, Jul 30 2003, 11:45:28)
[GCC 3.1 20020420 (prerelease)]
Type "copyright", "credits" or "license" for more information.
MacPython IDE 1.0.1
»>
Python on Red Hat Linux
Installing under UNIX-compatible operating systems such as Linux is easy if
you're willing to install a binary package. Prebuilt binary packages are available
for most popular Linux distributions, or you can always compile from source.
Download the latest Python RPM by going to
http://www . python. orglftp/pythonl and selecting the rpmsl directory within that.
Then download the RPM with the highest version number. You can install it with
the rpm command, as shown in Listing 1-2.
6
Installing Python
Listing 1-2. Installing on RedHat Lima 9
localhost:-$ su -
Password: [enter your root password]
[root@localhost root]# wget http://python.org/ftp/python/2.3/rpms/redhat-9/
python2.3-2.3-Spydotorg.i386.rpm
Resolving python.org ... done.
Connecting to python.org[194.109.137.226]:80 ... connected.
HTTP request sent, awaiting response ... 200 OK
Length: 7,495,111 [application/octet-stream]
[root@localhost root]# rpm -Uvh python2.3-2.3-Spydotorg.i386.rpm
Preparing... ########################################### [100%]
1:python2.3 ########################################### [100%]
[root@localhost root]# python (1)
Python 2.2.2 (#1, Feb 24 2003, 19:13:11)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2
Type "help", "copyright", "credits", or "license" for more information.
»> [press Ctrl+D to exit]
[root@localhost root]# python2.3 (2)
Python 2.3 (#1, Sep 12 2003, 10:53:56)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits", or "license" for more information.
»> [press Ctrl+D to exit]
[root@localhost root]# which python2.3 (3)
/usr/bin/python2.3
(1) Whoops! Just typing python gives you the older version of Python-the
one that was installed by default. That's not the one you want.
(2) At the time of this writing, the newest version is called python2.3. You'll
probably want to change the path on the first line of the sample scripts to point
to the newer version.
(3) This is the complete path of the newer version of Python that you just
installed. Use this on the #! line (the first line of each script) to ensure that scripts
are running under the latest version of Python, and be sure to type python2. 3 to
get into the interactive shell.
Python on Debian GNU/Linux
If you are lucky enough to be running Debian GNU/LimlX, you install Python
through the apt command, as shown in Listing 1-3.
7
Chapter 1
Listing 1-3. Installing on Debian GNUlLinux
localhost:-$ su -
Password: [enter your root password]
localhost:-# apt-get install python
Reading Package Lists ••• Done
Building Dependency Tree ••. Done
The following extra packages will be installed:
python2.3
Suggested packages:
python-tk python2.3-doc
The following NEW packages will be installed:
python python2.3
o upgraded, 2 newly installed, 0 to remove and 3 not upgraded.
Need to get OB/2880kB of archives.
After unpacking 9351kB of additional disk space will be used.
Do you want to continue? [V/n] V
Selecting previously deselected package python2.3.
(Reading database ••• 22848 files and directories currently installed.)
Unpacking python2.3 (from ••• /python2.3_2.3.1-1_i386.deb)
Selecting previously deselected package python.
Unpacking python (from .•• /python_2.3.1-1_all.deb)
Setting up python (2.3.1-1) •.•
Setting up python2.3 (2.3.1-1) •.•
Compiling python modules in lusr/lib/python2.3
Compiling optimized python modules in lusr/lib/python2.3
localhost:-# exit
logout
localhost:-$ python
Python 2.3.1 (#2, Sep 24 2003, 11:39:14)
[GCC 3.3.2 20030908 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
»> [press Ctrl+D to exit]
Python Installation from Source
If you prefer to build from source, you can download the Python source code
from http://WtM •python. orgl ftp/python/. Select the highest version number listed,
download the . tgz file, and then do the usual configure, make, make install dance,
as shown in listing 1-4.
8
Installing Python
Listing 1-4. Installing Python from Source
localhost:-$ su -
Password: [enter your root password]
localhost:-# wget http://www.python.org/ftp/python/2.3/Python-2.3.tgz
Resolving www.python.org ... done.
Connecting to www.python.org[194.109.137.226]:80 ... connected.
HTTP request sent, awaiting response ... 200 OK
Length: 8,436,880 [application/x-tar]
localhost:-# tar xfz Python-2.3.tgz
localhost:-# cd Python-2.3
localhost:-/Python-2.3# ./configure
checking MACHDEP •.. linux2
checking EXTRAPLATDIR ...
checking for --without-gcc •.• no
localhost:-/Python-2.3# make
gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -03 -Wall -Wstrict-prototypes
-I. -I./Include -DPy_BUILD_CORE -0 Modules/python.o Modules/python.c
gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -03 -Wall -Wstrict-prototypes
-I. -I./Include -DPy_BUILD_CORE -0 Parser/acceler.o Parser/acceler.c
gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -03 -Wall -Wstrict-prototypes
-I. -I./Include -DPy_BUILD_CORE -0 Parser/grammar1.0 Parser/grammar1.c
localhost:-/Python-2.3# make install
/usr/bin/install -c python /usr/local/bin/python2.3
localhost:-/Python-2.3# exit
logout
localhost:-$ which python
/usr/local/bin/python
localhost:-$ python
Python 2.3.1 (#2, Sep 24 2003, 11:39:14)
[GCC 3.3.2 20030908 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
»> [press Ctrl+D to get back to the command prompt]
localhost:-$
9
Chapter 1
The Interactive Shell
Now that you have Python installed, what's this interactive shell thing you're
running?
It's like this: Python leads a double life. It's an interpreter for scripts that you
can run from the command line or run like applications, by double-clicking the
scripts. But it's also an interactive shell that can evaluate arbitrary statements and
expressions. This is extremely useful for debugging, quick hacking, and testing.
I even know some people who use the Python interactive shell in lieu of a calcu-
lator!
Launch the Python interactive shell in whatever way works on your platform,
and let's dive in with the steps shown in Listing 1-5.
Listing 1-5. First Steps in the Interactive Shell
>>> 1 + 1 (1)
2
»> print 'hello world' (2)
hello world
»> x = 1 (3)
»> y = 2
»> x + y
3
(1) The Python interactive shell can evaluate arbitrary Python expressions,
including any basic arithmetic expression.
(2) The interactive shell can execute arbitrary Python statements, including
the print statement.
(3) You can also assign values to variables, and the values will be remem-
bered as long as the shell is open (but not any longer than that).
Summary
You should now have a version of Python installed that works for you.
Depending on your platform, you may have more than one version of Python
installed. If so, you need to be aware of your paths. If simply typing python on the
command line doesn't run the version of Python that you want to use, you may
need to enter the full pathname of your preferred version.
Congratulations, and welcome to Python.
10
CHAPTER 2
Your First Python
Program
You KNOW HOW OTHER books go on and on about programming fundamentals,
and finally work up to building a complete, working program? Let's skip all that.
Diving In
Listing 2-1 shows a complete, working Python program. It probably makes
absolutely no sense to you. Don't worry about that, because we're going to dis-
sect it line by line. But read through it first and see what, if anything, you can
make of it.
NOTE You can download this code. and all o/the other examples used in
this book. from the Downloads section of the Apress web site (http://ww .
apress. com).
Listing 2-1. odbche/per.py
def bui1dConnectionString(params):
"""Build a connection string from a dictionary of parameters .
Returns string."~"
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if name ==" main ":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret" \
print bui1dConnectionString(myParams)
11
Chapter 2
Now run this program and see what happens.
• Running programs on Windows: In the ActivePython IDE on Wmdows, you
can run the Python program you're editing by choosing File ~ Run (or press-
ing Ctrl-R). Output is displayed in the interactive window.
• Running programs on Mac OS: In the Python IDE on Mac OS, you can
run a Python program by selecting Python ~ Run window... (or pressing
Command-R), but there is an important option you must set first. Open
the . py file in the IDE, pop up the options menu by clicking the black tri-
angle in the upper-right corner of the window, and make sure the Run as
_main_option is checked. This is a per-file setting, but you'll only need
to do it once per file.
• Running programs in UNIX: On UNIX-compatible systems (including Mac
OS X), you can run a Python program from the command line. To run the
one shown in Listing 2-1, enter python odbchelper .py.
The output of odbchelper.py will look like this:
server=mpi1grim;uid=sa;database=master;pwd=secret
Declaring Functions
Python has functions like most other languages, but it does not have separate
header files like C++ or interface/implementation sections like Pascal. When you
need a function, just declare it and code it, like this:
def bui1dConnectionString(params):
Note that the keyword def starts the function declaration, followed by the
function name, followed by the arguments in parentheses. Multiple arguments
(not shown here) are separated with commas.
Also note that the function does not define a return datatype. Python func-
tions do not specify the datatype of their return value; they do not even specify
whether or not they return a value. In fact, every Python function returns a value.
If the function ever executes a return statement, it will return that value; otherwise,
it will return None, the Python null value.
12
Your First Python Program
NOTE Python vs. V'lSltnl Basic return values: In Visual Basic, functions (that
return a value) start with function, and subroutines (that do not retum a value)
start with sub. There are no subroutines in Python. Everything is afunction,
allfunctions return a value (even ifit's None), and all functions start with def.
The argument, params, does not specify a datatype. In Python, variables are
never explicitly typed. Python figures out what type a variable is and keeps track
of it internally.
NOTE Python vs./alla return values: In Java, C++, and other statically typed
languages. you must specify the datatype of the function return value and each
function argument. In Python. you never explicitly specify the datatype ofany-
th ing. Based on what value you assign, Python keeps track of the datatype internally.
How Python's Datatypes Compare
to other Programming Languages
An erudite reader sent me this explanation of how Python compares to other
programming languages:
• Statically typed language: A language in which types are fixed at compile
time. Most statically typed languages enforce this by requiring you to
declare all variables with their datatypes before using them. Java and C are
statically typed languages.
• Dynamically typed language: A language in which types are discovered at
execution time; the opposite of statically typed. VBScript and Python are
dynamically typed, because they figure out what type a variable is when
you first assign it a value.
• Strongly typed language: A language in which types are always enforced.
Java and Python are strongly typed. Uyou have an integer. you cannot
treat it like a string without explicitly converting it.
• Weakly typed language: A language in which types may be ignored; the
opposite of strongly typed. VBScript is weakly typed. In VBScript, you can
concatenate the string . 12' and the integer 3 to get the string '123 ' , and
then treat that as the integer 123, all without any explicit conversion.
So Python is both dynamically typed (because it doesn't use explicit datatype
declarations) and strongly typed (because once a variable has a datatype. it
actually matters).
13
Documenting Functions
You can document a Python function by giving it a doc string, as shown in
Listing 2-2.
Listing 2-2. Defining the buildConnectionString Function's doc string
def buildConnectionString(params) :
"""Build a connection string from a dictionary of parameters .
Returns string."""
Triple quotes signify a multiline string. Everything between the start and end
quotes is part of a single string, including carriage returns and other quote char-
acters. You can use them anywhere, but you'll see them most often used when
defining a doc string.
NOTE Python vs. Perl quoting: Triple quotes are also an easy way to define
a string with both single and double quotes, like qql .. . 1 in Perl.
Everything between the triple quotes is the function's doc string, which doc-
uments what the function does. A doc string, if it exists, must be the first thing
defined in a function (that is, the first thing after the colon). You don't technically
need to give your function a doc string, but you always should. I know you've heard
this in every programming class you've ever taken, but Python gives you an added
incentive: the doc string is available at runtime as an attribute of the function.
NOTE Many Python IDes use the doc string to provide context-sensitive
documentation, so that when you type a function name, its doc string
appears as a tool tip. This can be incredibly helpful, but it's only as good as the
doc strings you write.
Further Reading on Documentation
Refer to the following for more information about doc strings:
14
Your First Python Program
• PEP 257 (http://www. python. org/peps/pep-0257 •html) defines doc string
conventions.
• Python Style Guide (http://www •python. orgl docl essaysl sty leguide. html)
discusses how to write a good doc string.
• Python Tutorial (http://www •python. orgl docl current/tut/tut. html) dis-
cusses conventions for spacing in doc strings (http://www •python. orgl
doc/current/tut/node6.html#SECTION006750000000000000000).
Everything Is an Object
In case you missed it, I just said that Python functions have attributes, and that
those attributes are available at runtime.
A function, like everything else in Python, is an object.
Open your favorite Python IDE and follow along with the example presented
in Listing 2-3.
Listing 2-3. Accessing the buildConnectionString Function's doc string
»> import odbchelper (1)
»> params = {"server":"mpilgrim", "database":"master", "uid":"sa",
"pwd": "secret"}
»> print odbchelper.buildConnectionString(params) (2)
server=mpilgrim;uid=sa;database=master;pwd=secret
»> print odbchelper.buildConnectionString. __doc__ (3)
Build a connection string from a dictionary
Returns string.
(1) The first line imports the odbchelper program as a module-a chunk of
code that you can use interactively or from a larger Python program. Once you
import a module, you can reference any of its public functions, classes, or attrib-
utes. Modules can do this to access functionality in other modules, and you can
do it in the IDE, too. This is an important concept, and we'll talk more about it in
Chapter 4.
15
Chapter 2
(2) When you want to use functions defined in imported modules, you need
to include the module name. So, you can't just say buildConnectionString; it must
be odbchelper. buildConnectionString. If you've used classes in Java, this should
feel vaguely familiar.
(3) Instead of calling the function as you would expect to, you asked for one
of the function's attributes: doc .
NOTE Python vs. Perl import: import in Python is like require in Perl.
Once you import a Python module, you access its functions with
module. function. Once you require a Perl module, you access its functions
with module: : funct ion.
The Import Search Path
Before we go any further, I want to briefly mention the library search path. Python
looks in several places when you try to import a module. Specifically, it looks in all
the directories defined in sys. path, as you can see in the example in listing 2-4.
This is just a list, and you can easily view it or modify it with standard list methods.
(You'll learn more about lists in Chapter 3.)
Listing 2-4. Import Search Path
»> import sys (1)
>>> sys.path (2)
[", '/usr/local/lib/python2.2', '/usr/local/lib/python2.2/plat-linuX2',
'/usr/local/lib/python2.2/lib-dynload', '/usr/local/lib/python2.2/site-packages',
'/usr/local/lib/python2.2/site-packages/PIL' ,
'/usr/local/lib/python2.2/site-packages/piddle']
»> sys (3)
<module 'sys' (built-in»
»> sys.path.append('/my/new/path') (4)
(1) Importing the sys module makes all of its functions and attributes
available.
(2) sys. path is a list of directory names that constitute the current search
path. (Yours will look different, depending on your operating system, what ver-
sion of Python you're running, and where it was originally installed.) Python will
look through these directories (in this order) for a . py file matching the module
name you're trying to import.
16
Your First Python Program
(3) Actually, I lied-the truth is more complicated than that, because not all
modules are stored as .py files. Some, like the sys module, are built-in modules
that are actually baked right into Python itself. Built-in modules behave just like
regular modules, but their Python source code is not available, because they are
not written in Python! (The sys module is written in C.)
(4) You can add a new directory to Python's search path at runtime byappend-
ing the directory name to sys. path, and then Python will look in that directory as
well whenever you try to import a module. The effect lasts as long as Python is
running. (We'll talk more about append and other list methods in Chapter 3.)
What's an Object?
Everything in Python is an object, and almost everything has attributes and
methods. All functions have a built-in attribute _doc_, which returns the doc
string defined in the function's source code. The sys module is an object that
has (among other things) an attribute called path.
Still, this begs the question. What is an object? Different programming lan-
guages define object in different ways. In some languages, all objects must have
attributes and methods; in others, all objects are subclassable. In Python, the defi-
nition is looser; some objects have neither attributes nor methods (more on this in
Chapter 3), and not all objects are subclassable (more on this in Chapter 5). But
everything is an object in the sense that it can be assigned to a variable or passed
as an argument to a function (more on this in Chapter 4).
This is so important that I'm going to repeat it in case you missed it the first
few times: Everything in Python is an object. Strings are objects. Lists are objects.
Functions are objects. Even modules are objects.
Further Reading on Objects
For more information about Python objects, see the following:
• Python Reference Manual (http://WWN . python. org/ doc/ current/ref)
explains exactly what it means to say that everything in Python is an object
(http://WWN . python. org/ doc/ current/ref / objects. html), because some peo-
ple are pedantic and like to discuss this sort of thing at great length.
• eff-bot (http://WWN . effbot. ~rg/guides) summarizes Python objects
(http://WWN.effbot.org/guides/python-objects.htm).
17
Chapter 2
Indenting Code
Python functions have no explicit begin or end, and no curly braces to mark
where the function code starts and stops. The only delimiter is a colon (:) and
the indentation of the code itself, as shown in Listing 2-5.
Listing 2-5. Indenting the buildConnectionString Function
def buildConnectionString(params):
"''''Build a connection string from a dictionary of parameters.
Returns string. """
return "j" .join(["%s=%s" % (k, v) for k, v in params.itemsO])
Code blocks are defined by their indentation. By code block, I mean functions,
if statements, for loops, while loops, and so forth. Indenting starts a block, and
unindenting ends it. There are no explicit braces, brackets, or keywords. This
means that whitespace is significant and must be consistent. In this example, the
function code (including the doc string) is indented four spaces. It doesn't need
to be four spaces; it just needs to be consistent. The first line that is not indented
is outside the function.
Listing 2-6 shows an example of code indentation with if statements.
Listing 2-6. if Statements
def fac(n): (1)
print 'n =', n (2)
if n > 1: (3)
return n * fac(n - 1)
else:
print 'end of the line'
return 1
(1) This is a function named fac that takes one argument, n. All the code
within the function is indented.
(2) Printing to the screen is very easy in Python: just use a print statement. print
statements can take any datatype, including strings, integers, and other native types
like dictionaries and lists that you'll learn about in Chapter 3. You can even mix and
match to print several items on one line by using a comma-separated list of values.
18
Your First Python Program
Each value is printed on the same line, separated by spaces (the commas don't print).
So when fib is called with 5, this will print n = 5.
(3) if statements are a type of code block. If the if expression evaluates to
true, the indented block is executed; otherwise, it falls to the else block.
(4) Of course, if and else blocks can contain multiple lines, as long as they
are all indented the same amount. This else block has two lines of code in it.
There is no other special syntax for multiline code blocks-just indent and get
on with your life.
After some initial protests and several snide analogies to Fortran, you'll
make peace with this and start seeing its benefits. One major benefit is that all
Python programs look similar, since indentation is a language requirement and
not a matter of style. This makes it easier to read and understand other people's
Python code.
NOTE Python vs. Java statement separation: Python uses carriage returns to
separate statements, and a colon and indentation to separate code blocks.
C++ andjaua use semicolons to separate statements and curly braces to sepa-
rate code blocks.
Further Reading on Code Indentation
For more information about Python code indentation, see the following:
• Python Reference Manual (http://www . python. org/ doc/ current/ref) dis-
cusses cross-platform indentation issues and shows various indentation
errors (http://www.python.org/doc/current/ref/indentation.html).
• Python Style Guide (http://www . python. org/ doc / essaysl s ty leguide. html)
discusses good indentation style.
Testing Modules: The if name Trick
Python modules are objects and have several useful attributes. You can use this
to easily test your modules as you write them. Here's an example that uses the if
_name_ trick:
if main
- name-
n.
19
Chapter 2
Some quick observations before we get to the good stuff. First, parentheses
are not required around the if expression. Second, the if statement ends with
a colon and is followed by indented code.
NOTE Python us. C comparison and assignment: Like C, Python uses == for
comparison and =for assignment. Unlike C, Python does not support in-line
assignment, so there's no chance of accidentally assigning the value you
thought you were comparing.
So why is this particular if statement a trick? Modules are objects, and all
modules have a built-in attribute _name_. A module's _name_ depends on how
you're using the module. If you import the module, then _name_is the module's
filename, without a directory path or file extension. But you can also run the
module directly as a stand-alone program, in which case _name_ will be a spe-
cial default value, _main_.
»> import odbchelper
»> odbchelper ._name_
'odbchelper'
Knowing this, you can design a test suite for your module within the mod-
ule itself by putting it in this if statement. When you run the module directly,
_name_ is _main_, so the test suite executes. When you import the module,
_name_is something else, so the test suite is ignored. This makes it easier to
develop and debug new modules before integrating them into a larger program.
TIP if_ name_ on Mac OS: On MacPython, there is an additional step to
make the if _name_trick work. Pop up the module's options menu by click-
ing the black triangle in the upper-right corner of the window, and make sure
Run as main is checked.
Further Reading on Importing Modules
See the following for more information about importing modules:
• Python Reference Manual (http : //www.python.org/doc/current/ref)
discusses the low-level details of importing modules
(http://www.python.org/doc/current/ref/import . html).
20
Your First Python Program
Summary
Some of the odbchelper.py you saw at the beginning of this chapter should make
more sense to you now. You should recognize Python functions. You know that
everything in Python is an object. The next chapter will explain the other parts of
this sample program.
21
CHAPTER 3
Native Oatatypes
WE'LL GET BACK TO your first Python program (from the previous chapter) in just
a minute. But first, a short digression is in order, because you need to know about
dictionaries, tuples, and lists (oh my!). If you're a Perl hacker, you can probably
skim the bits about dictionaries and lists, but you should still pay attention to the
information about tuples.
Introducing Dictionaries
One of Python's built-in datatypes is the dictionary, which defines one-to-one
relationships between keys and values.
NOTE Python us. Perl dictionaries: A dictionary in Python is like a hash in
PerL In Perl, variables that store hashes always start with a %character. In
Python, variables can be named anything, and Python keeps track of the
datatype internally.
NOTE Python us. Java dictionaries: A dictionary in Python is like an
instance of the Hashtable class in Java.
NOTE Python us. Visual Basic dictionams: A dictionary in Python is like an
instance of the Scripting. Dictionary object in VisuaL Basic.
Defining Dictionaries
Listing 3-1 shows an example of a dictionary definition.
Listing 3-1. Defining a Dictionary
»> d = {"server":"mpilgrim", "database":"master"} (1)
»>d
{'server': 'mpilgrim', 'database': 'master'}
»> d["server"] (2)
'mpilgrim'
23
Chapter 3
»> d["database"] (3)
'master'
»> d["mpilgrim"] (4)
Traceback (innermost last):
File "<interactive input>", line 1, in ?
KeyError: mpilgrim
(1) First, you create a new dictionary with two elements and assign it to the
variable d. Each element is a key/value pair, and the whole set of elements is
enclosed in curly braces.
(2) 'server' is a key, and its associated value, referenced by d[" server"], is
'mpilgrim' .
(3) 'database' is a key, and its associated value, referenced by d["database"],
is 'master' .
(4) You can get values by key, but you can't get keys by value. So d["server"] is
'mpilgrim' , but d["mpilgrim"] raises an exception, because' mpilgrim' is not a key.
Modifying Dictionaries
Listing 3-2 shows an example of modifying a dictionary.
Listing 3-2. Modifying a Dictionary
»>d
{'server': 'mpilgrim', 'database': 'master'}
»> d["database"] = "pubs" (1)
»>d
{'server': 'mpilgrim', 'database': 'pubs'}
»> d["uid"] = "sa" (2)
>>> d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'pubs'}
(1) You cannot have duplicate keys in a dictionary. Assigning a value to an
existing key will wipe out the old value.
(2) You can add new key/value pairs at any time. This syntax is identical to
modifying existing values. (Yes, this will annoy you someday when you think
you're adding new values but are actually just modifying the same value over
and over, because your key isn't changing the way you think it is.)
Notice that the new element (key uid' , value sa') appears to be in the mid-
I I
dle. In fact, it was just a coincidence that the elements appeared to be in order in
the first example; it is just as much a coincidence that they appear to be out of
order now.
24
Exploring the Variety of Random
Documents with Different Content
gaudioque plenns evadat , confimilcfque altcratfoncs >
reformationes , pcrmucaciones feu vicisficudines in nacura hominis
continganc» A R T I S T A. Minimegentium ,Domine. Potcftas quippe
tantanulli unquamcondonata Medicamento eft, ut hominis naturam
mutare valeac. Enimvcro Vinum inebrians a diverfis fumptum
Individuis in ebriofonaturamhominis nonmucavit, fed tantummodo
provoca vit, quod in ipfo naturaliter potentialiterque inefl: , atque in
adlum deduxic, quod quafi mortuum in ipfo fuerac. Eodem fe modo
habet operatioMedicinae Univerfalis,quippe qus per Spirituum
vitaliumrecreationemprovocacfanicatemad tempusduntaxat in
hominefuppreflam, utpoteinquoantea naturaliter fuerat, pcrinde atqj
SoHscalorherbasautfloresnon immutat , fed eosdemfaltem provocat,
atqueexpropria ipforum natura potentiah inadum faltcm revocat.
Melanchoiicasnamquctemperatura^homoin fuasdenuo
rcsmelancholicasrefufcitatur , &:ver6 homojovialishilarifquein fuis
aftionibus Isetis recreatur, atque ita confequenter :
Prsefervativumquein defperatis morbis omnibus eft prasfentaneum
feu optimum. Hincpraeiagiensobventurumfibi fore quippiam adverfi ,
mavult prasvenire quam pra^veniri. Quinimo Ci ulla daretur Vkx p
olongatio per Medicamentum quoddam Philofophicum contra
tacalemDeiomnipocencispraedcftinacionem , cerceprofedonoft
Mercurius Trismegistus , nequcPARACELSus , neque Raymundus
Lullius , nequeComcs Bernhardus , neque confimiles illuflres hujus
Myfterii Magni pofleflTores complures morcem mortaliu.m reliquorum
communem oppetiifilcnt , fed forfitanfuam m hodiernumdiem ufque
vitam procraxiflenc. Ergofanatici ac lymphacici forct hoc perfcribere ,
imo ftolidiflimi , idem credere ac fentire de uno aliquo
Medicamcntorum in tota rerum nacura. Ppp pp 3 ME
The text on this page is estimated to be only 28.23%
accurate
8^4 Pitulm j^ureus] M E D I C U S, ^ Qu3eciinquc,mi
Amice,de Univerfalis Medicinse operatione non minus rcgaliter quam
fundamentaliter dixifti , L^tus lubenfque conceiTerim
quidemego,fedquandiulaboro ignorantia
prseparandiredeillam,nihilagonifudcmquod cymbam exiguo ludere
cupienslacuin Occannmvaftum,quippequicerteadillam inde fme
ullofrudtu reddendam littori compclletur. £t quamvis enim de laudata
illa Prseparatione plasrique virorum illuftrium nonnihil confcripferint
jilludtamentali quafi cautionisumbrofas carbafo involverunt , ut
Le^lorum afTiduorum paucifTimis innotuerintveftigia ipforum
latenter demonftrata, quse lequenda tantifper forent , dum
pcrvenirentj quopcrvcllent. Quoiufquifqueetiam tot inftrudus
eftfumptibus,quotpoflitlibicoemerecodicesillosomnes , inquibus
fparfim de iftiufmodi Hypothefi ita tradtatur, ut illis perlegendis
rnaximamvitsebrevisparteminfumas,antequam inde {ufficientem tibi
cofynitionem manualemque operationcm coUigas. Maneamus
i2;iturinnoftroLaboratorio, aDcoetiambcnedi(^o , juxtaillud; Or^ AC
Ldora 5 c^ Dm dat omni hora. ARTISTA ELIAS. Satis rcde
argumcntaris , Domine j ex Philofophorum
namnuefcriptisrariftimeaddifcitur h*EC Ars Artium , fed perbene ac
clare exmanududionealicujus Adepti intelligitur fenfus ipforum.
Tranfcamusautem hinc ad MetaUicumhujusnGbiliffimieTinctuXX
EftedumTranfmutativumjdc quo Participcs feu Adepti confcripferunt
libros multi multos, atque plerique ipfbrum difcipuh genuini
inlgnemultum laborantcs ad finem Arcaniipforumpra^optatum albis,
quod dicicur, avibus pervenerunt. M E D I C U S. Animadverto,
Dominationem Vcftram trahi volupta tc transcundi
The text on this page is estimated to be only 19.48%
accurate
Pitulus Atireui, S^f cundi a Mcdicinas Ufu ad
Tranfmiitationcm Mctallorum infinitam. Cseterum quamvis ego faiclc
credere poflim Pollibilitatem Artis , dari nimirum inter A d E p t o s
Experimentum i{\i\\x[modi Chymicumjproutetiaminfuperioribus
mentionem fccidcilJo ExperimentOjquandoDn. DodorKiF L E RU s
obfletricante unius uncia: Auri Tin^lura in Aurum optimum
tranfmutavit unciam unamfemis Argc«iti; utnihil infuper dicam de
Experimento H e lMONTir,nequeScoTiinceleberrimiscivjtatibus
Colonia S>C H A N o V I vE, neque de illuflri ac pervagato illo
Excmplo maximo, quodpRAG^coramCsEfareFERDiNANDo IIL
mediante unico Tindlurar grano libr^e Mercurii tres funt in Aurum
nobiliilimum tranfmutat^jUfqueadeoutegononrainusin neceflitatem
quam in voluntatem credendi adducar , Artem efleVeram pofle,
etiarofi pleiionondumfulfragiofufficienterconciperequeam ,
utpotequiposfeflbrem ejus verum nunquam per vitam mcam omnem
his raeis ocuhs vidi* A R T I S T A. MiDomine,Verum dixifti, Artem
tamenfore Artem, etfamiitucrcdere abnueres ; haud fecus atque in
Magnetevidere eft $ quemadmodum illcper fuan^. fibi infitam vim
falphuream ex fcrro per contadum flatimmagnetemfacit, etiamfl
credere tu nolis, kccnterinipfotammiras ineffe operationes , tamen
veras permanebuntrltaeciamdeLapidePhilofophorum habeto , cui
intusineft, quicquid quasrunt Sapientes > 6c quonian^ caliginofa
ipfbrum fcripca apauciffimisin veftigotorum infelligi& explanaripoflunt
j votis erac omnibusoptandum,manibu/quecon:.ndum ,unam aliquam
totius ArtisEpicomenLaconicamitaconheri , L?t inde exiguo tetnporis
fpacioaclaborepauculoomnia combibineceffariaposfint,quorum
adminiculo cranfitus ad Autores reales detur facillimus. Qupd
quumjam inmediumexempIaprotulerijnonnulIa,ex
quibuscon«icebarJspecereconfirmandamrei afleverarepc>sfibilitacem
, jam ijpfe^
The text on this page is estimated to be only 25.24%
accurate
ipfemct tibi ego commonftrabo veram
SecretorumPhilorophoriim Materiam. EHam 1 Proba. M E D I C U S.
H3eccine,mi Domine, imo ha^cipfa fubftantia fulphureaquc
flavaqucvitreaqueeftMateria Philofophica ? Numnam tute ex ipfemet
fcientias hujuspofteftbr ? Crcdofane, quod mc ludiferis. Qusefo
Domine , dic mihi veritatcm , Utrum res kk ita habeatj necne i
ARTISTA ELIAS. Im6,Dn. Dodor^PreciofifTimumMundiThefaurum ,
jam in tuis habes manibus. Quia hic eft Verus Lapis
Philofophorum.quo nemo alter habuit unquam mehorem ,neq,
habebit aiium : atq; ego
metelaboraviipfeCompofitionemabinitioadfincm ufquc. Quod
fitibiconclaveadhuceftaUud , oftendam tibiMetalkimabifthoc Lapidis
generc tranfmutatum in Aurum, Quorfum introdudus, ^dlhice\ix\
(\'^ix.ihas quinque 7aleola^ utpote heneficio ipfius Jm^urx
VhilofophtCA ex Sdturmfeu PlumbopAratos, cjtiostnperpetuam
KjMagiJiri meimemoriantgefio. Tibivero, quimultaperlcgifti Adeptorum
fcripta,ex vifahujusLapidis fubftantia&:naturafat beneconftarc poterit
notitia de Materia vera. M E D I C U S. Quantumexte inaudio,
Magiftrum habuifti , a quo Artcm potius condidicifti quam
propriolabore atque invcntionc acquifivifti. Verumenimvcrotametfi
egojamiftam (ubftantiam , quam cileTinduram
Philofophicamverampra2dicas,confpexerim juxta cum TaleoHs his
quinque aureis ; relinquor tamen etiamnum ignarus ac dubius ,
utrum vcrum fit nec ne. Quocirca maximopere a te etiam atque
etiam peto , ut mihi condonare velis tantillum illius Materix fruftulum
, quantillum fufficiat ad tranfmutandum quatuor I
The text on this page is estimated to be only 29.19%
accurate
tuorfalcem grana pliimbi iu Aurum, uthocpadomihi
fcrupuhim dubicationisomnemeximasatquc me canco cerciorom
dcRci veritacc rcddas. Eccc | capefis fruftulum complcns
magnicudincm qniusfalcemgranifeufeminis cannabini,ucinde
fiveinmorbo ahquo defpcraco, fivcin Mccalhca
Tranfmucacioneipecimcn feu Proba exhiberiponic. ARTISTA ELIAS.
Faceor,qucndambon5C condftionis virum atquc mihiprorfus
incognicunumonftrando mepcrdocuiflTc i. PolTibilicaccm
Tranfmutacionis. 2. Pras^parandi quoque Modum : acquc hxc cft
Arsifta infanibihs,dequacibinullacenuscftdubicandum. Ucaucem
cantillum fruftuli, quancillum pecis , cibi condoncm , nullis mihi
modis hcicum eft, eciamfi vel coc ducacos mihi rcdonarc velles ,
quoc cora hxc camera capere poflec ab imo ad fummum ufque,
idque non propcera:ftimationcmmaceriar,quippequaj nulhus cft
prccii, fcdpropcer aham quandam racionem momentofam , cujus
refpcdufi fieri poflec,uc ignis ignc cxuri valcret; , cgo jam cum dido
tocamhanc mafTamprac cuisoculis inflammas cjus edaces
conjiccrem. Quare incerim a te peco , uc adeo avarus fciencix canca:
capcanda: effe nohs. Quia hic plus penes me tu vidifti hodie , quam
multi Rcgum Principumquc alibi fpedare voluerunc , fcd nunquam
confpicere pocuerunc. Cajccrum medicor mecum dc rcdicu ad ce,
incerjed:o crium fepcimanarum curriculo^ubi cibi in ArteChymica
Arces quasdam pulcherrimasjuxcaacque manududioncs monftrabo.
Quinetiam fi cunc ccmporis conccffum raihi fucric,
uccibiTranfmucacionemoftendam, Curiofitati tua: afFacim fatisfaciam.
Intcrim valereacfalveretejubcnspeco, uc cibi a cahlaborc
magnoarduoquecaveas, nefamampariceracqucfubftanciam tuamin
cincribus mifcre difperdas fimilicer aliquam mulcis avaris ejusdcm
Artis fummx Inquifitoribus. Q^q qq ME
The text on this page is estimated to be only 19.02%
accurate
%s Pitiiks Jmeui^ M E D I C U S. Nnnc quid faciam, mi
Dofmine ? Siforrafle Tibi ex Philofophico tuo Turameiuo confirmato
ifla potmncula argenti in aqua pUi via eiiiioluti licitum non ilt, ut
doncs mihi iftud tniflulumTinLlui;a: miXX , certe refcifcas, quod,
prout m rufpicaris yCgo rum animo^anxius
£nixequeavidusScicnria:hujus prxnobiliscombibendx,(Sjcrcdo, quod
vel ipfe primus Mundi Patriarcha Adani olim ob comcftum
iitriufqueSophii^malum exParadiib cxterminatus [fiadhucinvivis
liacnoilraciretsetate] nullus intermiflurus forec , quin denuo de
hocmaloaureoexATL ANTis hortc coracdere pcrvcllct. ' . Veftra
Dominatio inquit, Hoc multos Vrincipnm nonfotuilje
.viderCyqucdegovidL VidiequidcmegoMateri5m,de quatutamrara
prxdicas, interim vero non confpexi EfFcdum Tranfmutativum >
Diliquod tuis fidemadhibcam verbis. Quod quumDominatio
veftramefoIeturyfequidemjam.hinGprofcdurum,fed inrerfapfo
trimTihebdomadum.fpacioadmerediturum,ucmihiArtesCh7micasperpu
lchras juxtaatqucprojedionem ,filicitum fuerit, comraoii^ ftrct , hujus
bonae fpei fruitione cgo hac vice acquiefcens, gratias interimtibiago
ampliffiraas pro tuamihi exhibita Amicitia maxima:,
finf^ulariquefideipr^emonentiscura, utinLabores Chymicos Famam
fortunafqucmeas omnesne profiimdam atqucdilapidem amiffurus.
Certe ego tantorum Arduorum nondum ullum feci unquam
periculum, neque attentaturus fum, nifi prius Dominatio Veftramihi
orratis atque expura Amicitise benevolentia demoftflrare' voluerit
praeparandi modum ac viam. Interim vero Veritatem Artisadmiror ,
atqueetiam fpedatar tuxin me Amicitia^ ratioBc mihi gratulor ,
utpote qui hoc mihi detexifti,Te Adeptum: cfle. Quod fi vel Rex vel
Princeps vel c^eterorum Magnatiin» quifquam confcirent aut
refcifcerent, Te Artis hujus poflefToreraf d]^,.atqueproiade te
^quGdDeusprohibeatJrapercntadqusflio
The text on this page is estimated to be only 20.36%
accurate
Piuilus Ameui. %^^ «em^&cruciarcnttefLiisTortoribus,
numnam Artcm eflcsapcrturusi A R T I S T A. Nemini unquam
aliasprajterquam iinialicuijfeni probo ac ja-. iloviro
juxtaactibiLapidemPhilofophorum monftravi,
atquemiimulrevelavijmepofTeflbrem efle:(ednemohominum
unquamimpofl:erum talequidvidereatq;audiredebet. Quinimo
etiamflquis Regum vel Principum me [quod fane Deum meum non
facile permillurumforeiperojefletinvinculaconjedurus ,
cgotamennequaquam , more circumforaneorum Mcdicorum
feplaflariorum» vagabundoruimpofl:orum feu paupertinorum
Alchimifliarum, ipfis Artemprodere veldirecbevclobhquevellem/ed
quavis truculentiflima fidicularum prunarumque vivarum torcura
cxcarnificari ^ excruciari atque enccari mailem. M E D I C U S.
AmiccboncdanturneAutores , qui dehujusArtisveriMrc fcribunt
explanatius iilismultisomnibus, quitamobfcura
deilJaerudantvcrbajUteademveiip{imetfortairenonintel]igaut,nificomin
entarios annotationefq; cvidentiorum adhibeant Paraphrafbrfi 5
quemadmodum tu forfltan a pofteriorepcrlegiflijatqueproindeomnium
optimecalles, qualcs vcrifint Adepti. A R T I S T A. DomineDocl-or ,
librosquidcmegononlego , ncqueperlcd multosjmukos tameninter
alios Autorcs non oftendi curioflorcm Sendivogio , nominatim autem
in hbro qui infcribicur Cofmopolita^ Bclgice Borgerdek^W^erelt. Nec
non fratrcm BASiLiuMinfuisxii. Clavibus. Qiianrum ad Sendivocium
attinet.hunc Autorem utendum habeb]s,fimui atque rediero,prout
dixi : utpotcin cujus verbisobfcurisdelitefcitverftas , perinderan
The text on this page is estimated to be only 26.53%
accurate
quam in MineralibusMetallicifquc Corporibus cxternis, ctiam
aoftra Philofophor um Tind ura cft inclufa atquc retrufa. M E D I C U
S. •■•f Gratiam tibi,Dominc,habco pro tanta amicitia maximam.
Interea loci vel exfpedabo,quarcunq> pollicitus es; &:
quodDominatio veftradeTinclurxObjedisedifleruit , facile
aflentioraclargior , utpote qui credo, quod mkx efticacefque
Metallorum EfTenti^e ocGultantur fub externis Corporum corticibus
folliculifque , quanGuam perpaucos in Igne adeo exercitatos
expertofquc compctio , uc - fecundum Artis di^lamen cnuclearc
nucem lciant. EnimveroomneExternumrobuftumque cujufpiam
Animalis , Vcgetabilis aut Mineralis Corpus eft inftar tahs terreftris
Provinci2,in qualem, prout Ifaacus HolUndtu perfcripfit, Eflentiaj
prarclara: fpiritualiterimmigrent. Quocircaopuseft, ut
Artisfilii(ciant,quahtcrpcr Fermcntum falinum
quoddamidoncumMetalhcxqucnaturx gratum edomare, difloivere ,
feparare & conccntrare pofllnt non
magneticammodoVirtutemtingendi Metaflicam, (ed qualitctctiam
morePhilofophicoinfuohomogcneo Aurcovel Argentco eandera
muhiplicare valeanc Et videmus cnim , quod Creacuranim
Corporaomnium faeile non folum deftruuntur, fed protmus etiam ,
(imulatquelnterna viveredcfinunt,in Orcum tencbrafque antiquas
rapiuntur, in quibus latitabant, ancequam in lucem per Dei Creatoris
creationcm produccbantur. Quocufquifque autem hominum
eftnobishancinRegnoMetallico Artcni conimonftraturus? A R T 1 S T
A. Redle dixifti, & optime judicavifti de naturah rerum
deftruftionciatq; flDeo mifericordiflimo vifum placitumq; fuerit,ipfead
Te, perinde acquc mihi gratiofe faccre dignacus eft, vel cua fperancis
opinionecitiusnonncminem Adeptgrum ablegare poterir, qui Tibi
monftretPhilofophicumModum dcftruendiMetalla atq; colhgendi
gendi Animas ipforum Internas. Interim vero iivoca Deum
Opt» Klax.cujuspervigilisoculis tecommendo , identidem apertis fupcr
filiosfuosfibiperChriftumJefumregeneratosJteruro vale,atque fic
habe,me tibifore Amicum
permanfurum.Menamqueoportetrurfusproficifcihinc,fedfpero,rae
teefTebreviin florentefaoitatisflatu revifurum. Itanovusillemihivalcdixit
atque abiit Amicus, Amicum fuumrelinquensme rrifliflimum per
tempus trium feptimanarura , quibus exfpirantibusillc,
proutcondixerat, rediitatque Tin^luram jnihi dedit, quemadmodum
ex totaHifloria jam fupra vobisad pericgendum enarrata ac
praefcripta cognofcere potuiftis. Poftcaquam
illeHomoDeiPhilofophicusviciflim a me abierat , ego eundem
nunquam amphus revidi &: ne verbum quidem deeo ullumexaliquo
vcl pcgafariorum vel tabellariorum vel intinaoium audire potui.
Verumenimvero ipfe apud me pro flimuliy reliquit acrem fui
memoriamaltamenterepofitampariter atque opinionem Par ac E L s I
aflcverantis, quod per Metalla ex Metallis atque cum Mctallis
emundatis, Spiritualibus & ab ipfamet faece antea depuratis
fiantMetallaacAurum Argentumque Philofophorumvivum, tam ad
Corpora humana quam Metallica. Qupcirca fi hofpes ille
paucaeconverfationisamicusmihi exade monflrafTet Modum
prjepatandi hoc ccelefle Sal Spirituale, per quod &: cum quo ex
corporeis tcrreflribufquefubflantiispoflim quafi in eorum Matrice
coIJigere Spirituales SoIisautLunjeradios, certe ille defuo raihi lumine
lumen tantum accendiflet, ut videre & callere potuifTem , quomodo
Magneticeinaliis Metalliscorporeis Animamcorum Internam ita per
Symparhiam tranfmutare debuiflem, ut ipfiufmct ope corpus
ejusdemfibifimileclarificafrentfeu transformafTentvel in Aurum vel in
Argentum , fecundum feminis rubri indolem in Corpus rubrum,
autfecundumfeminisalbinaturaminCorpus album. Nam dixit mihiEiiAS
Artista, quod Sendi vogii Chalybs fit illa vcra Mcrcurialis humiditas
Mctaliica, qua adminiculante fine omni corQc[q qq 5 rciivo
The text on this page is estimated to be only 22.97%
accurate
rofivo in Tgne apcrto ciucibuloquc Artifex auri poflit fixos
Solis aut Lunit L-adios a fuo Corporc feparare , atque deinceps
voLuiles Mcrcurialesrcddcrcpro Tindura Piiilofophica
fjcca,qucmadmodumip(emihimonfl:ravit,atque nonnihil communicavit
ad transiiiutandumMctalla. Enimverohocmecum omnes dodaChymia:
cxpcrientiaimbutiafleverareatq-jConfirmareneceflehabent, quod
PYROTECHNiAcfl: matrix ac nutrix variarum nobilium
fcientiaxumartiumquc. llliquippeexcoloribusdeMetaliorum Chao in
Igrnefaciledijudicant,qualeipfiinritCorpusMetallicum. Itaenim
infin^ulosdicsadhucinterrx-gremioprocreantur Metalla , lapidefque
pellucidi ex proprio nobili femine vaporofo, fcminc Spiririiali tin^Tcnte
Sulphureo,in fuis diverfis matricibusfalinis. Nam Sulphurcommune
five Metalli alicujus puri vel impiiri,adhuc cum fuo corporc
conjun^lum, cum fale petra: duntaxatmixtum
interardentemi^nisfcrvoremfacileinduriffimam fixilTimamq; mutatur
terra. Terra verohicc deinceps vicifTimexaerc facile
inaquamlimpidiflimam mutaturA' l^i^rc Aqua poflmodum fortioreigne
fecundum admixtiSulphurisMetallicipuri autimpuri naturam ,
convcrtituria vitrum, coloribus variis perbelle tindum. Ad eundumfcre
modumex'ovialbumineprogigniturpulluspercaloremnatur2lem. Ita
ctiamexvinculo vitsefeminalialicujusMctalliconfitnovum idcmGue
nobilius Metallum, pcr calorem ignis Salini natura: convenientem-,
tametfi paucifrimi Chymicorum redeacperfccte fciant , quomodo
Internse Metallorum vires femper movcntcs magnetica: fccundum
fuam ipforum vel harmoniam vcl difcrepantiam dicantur ;
quarehocMetallumcumMetalloaltero Sympathiam vel
Antiparhiamhabcatadeofingularem , veluti videamusinMagnetecum
Fcrro,in Mercurio cum Auro, in Argcnto cum CuproSympathiam-,
impenfefinc^ularemicontravcronotabilis ofFcndatur Antipathiain
plumbocontra ftannumjinferro contraaurum, in Antimonioconcra
Arf^entumjinplumbo contraMercurium,&:confimilesaliaroccuriunt in
Regno Animali ac Vcgctabili Annotationes fexcent^e Sympathccica:
&: Antipathetic;e,prout l©gas ac rclegns in variis Autoribus
The text on this page is estimated to be only 16.08%
accurate
toribuSjqui perfcripferiint de iftiiifmodi Curiofitatibus ,- cx
quaruiTa
accurataabfolutaquccognitionecreanturatq;a:ftimanturveriPhi«
lofbphiatque Natur^e Magifiri, HiTCufque quod cgomct ipfc vi di &
fecij id dcfcripfi , excircfendumcuraviarque vobis, Candidi LccloreSjCX
mera liberalitater gratis commanicavi juxta illud Sencca^ : In hoc
fctre diquid dcfidero ^ ut diosdoceam. Sicnm hacExceptione detur
Sapientia , ut ilUm influ/amteneami ahjiciam. Quicunq> vero de vera
Vcritaterei dubitat, tantumodo in Jefum fuum crucifixum Fide viva
credat,nova in Ipfb creatura per viam Regcnerationisftridam fiat,in
Eodem anchoram Speiflia^omnemfigatt^ 7Tiav in quofvis proximos
pariteratque potiflimum opcra Mifericordi^e philadelphicx pia in
egena Chriflian^E
Religionismembrariteexcrceat,ufquedumpoflcurriculumvita^omnejuft
e fan£lcque confummatum horafua fatali ac
emortualihincperundabundtimMundihujus tcmpefluofi ac fcopulofi
Oceanumintutumtranquillumq; a^tcrni Sabbatismi beatislimi portum
falvus enavigetatque novum cum Philofophis cceleflis Hierofolymse
triumphantibus Canticum cantecr Participatupi ab ea cjul KefirHrrp
Omniurrf I FidelifHmus addidtifHmufque Johannes Frideriem
Hehetim, MedictnA Bo^or ^ Prticlicm Htt' g^Comttts, F I N I S. JANI
The text on this page is estimated to be only 21.14%
accurate
TANITOR PANSOPHVS. Seu Figura iEnea Quadripartita
Cun6tis Mufeum hoc Introeuntibus, Superiorum ac Infcriorum
Scientiam Mofaico-HcrmcCicam, analytice £xhibens.
The text on this page is estimated to be only 0.00%
accurate
'>»
The text on this page is estimated to be only 24.58%
accurate
FIGVRA l C SANCTrS \ SANCTfS'. SAN MAgnc
paterDlvum.Mundi SupremaPoteftas, Quo nihil efle potcft nec fingi
majus; ab omni Corpotca ftans raole pracul, tamen omnia fingenj
Corpora,velprorfusmutarincfcia, vel qux Temporis anfraifbu longo
labcfacla Uthifcunt : Principiumlinepnncipio,Fonsundc Bonorum
Eifluitomnegcnus, Naturi- Reclor & Auftor, Omniacomprcndens ,
atnoncomprcnfusab ullo. Majcfljs Iramcnfa, Bonum, Sapientia, Vita,
Ordo, Dccus, Finis, Mcns, Vcrum.Lux, Via, Virtus : Nufquam
habitans, &: ubique habitans : Immobilis, &: Jans Alfi Jue raotum
Cunclis : a quo Omnia &: in quem Omnia.pcr qucm etum funt Omnia
: lcmper eadem Conditionemancns, nuUo mutabilisxvo: CTrS
DOMINVS EXERClTfFM lOMNlS TERRA mtitneSits Pdingenius in Zod.
Vit. Lib. IX. Maxima Caufarum, qux certa lcge re volvens
Sidereammolem.farorumjuragubernas; Rcx Regum, cui Mille adftant,
6C MiUe miniflrant Agmina Divorura l.a:tantum hymnofque
canentura Lucisinlmmenfa:campis,extra ExtiraaMundi Mcenia, llbi eft
Veris fcdes aptiffima rebus : Te colo , Tc Veneror , Te nunc
reverenter adoro Atqueprecorfupplexutmefpeaarebenigno Digneris
Vultu, Voceraqueaudirc precantis. Mitte tus Lucis radios mihj, pelle
tenebras Oppreflje [ heu ] nimium moribundo in corpore mcntis, Da
teftam rcperire viam, ne noxius Error , Vanaque crcdulitas & Opinio
cxca trahat mc Pra:cipitem in falebras rcrum &: contagia Vita:.
REFLETA EST CIORIA ElVSl Nam Cne Te ingenium mortalc,
huraanaquc virwt Dum fe tollere humo (pcrat, Vclut Icarus olira
Disjunflacompage ruit pennisquefolutis: Necpotis cft finc Te Occulti
penetralia Vcri Cetnerc, necqua partefalus aut artc pctatur.
LargireErgoraihi,Rcx6 digniirimc Rcgum,
lItTecognofcam,&:placeamtibi : dcindc fciam Mc Quid fim, qua in
Terris caufa produdus &C undc Hucveni, actandemquo vita
funclusabibo: Quid mihi dum vivo fit agcndum : fitquc cavcndum :
UtcumfinieritLachefismeafila.diesque
lIltimusabdidcritraembraha:ccxhauftafepulcro, Mors fiat mihi grata
quics , portufque falutit. 0
The text on this page is estimated to be only 2.00%
accurate
$I/
The text on this page is estimated to be only 15.03%
accurate
riQVRA II JMVNDVS ELEMENTARIS 2 ^ •'iL D t^utcr
nnchmdii PhyfictReJliluU. Can. l. feq^ Eus eft Ens jCtcmum , Unitas
Infinica, Radicale Rcrum omnium Ptmcipium .- Cujus Effentuefl: Lux
Immcnfa : Potcftas Omnipotenti» ; Volun_ tas BonumPetfcaum:
Nutus Opus abfolutum. Piura deficlcratitjoccutruntftupor, Silcmium&
Abyffus Gloris profundiflimx. §. i. MunJum ab ^tcrno in Arclietypo
fuo dcfcijptum fuiac Sapicntum pliitjtni duxcrunt: Arclictypus autcm
[pfc qiiiTotus Lumcn eft.ante Univerfi Creationcm in fe complicatus,
ccu hber (ibi foli illux.t, in Mundi vero produftjoncnuafi partuticns fc
aper.ut & explicuit, Opufq, fuum in Mcnte, velut in matricc. prius
occultum, o.uadim fu. Extcnlione raanifeftum fccit ac Mundum
Idjjlem, quafi duplicata Divinitaiis Imagine , adualcm & matcrialcm
cduxit. Hocannuitrr««di/fiferw,,»ffirmAvit. i.4.Qm
fi.mmumiusUnivcrliinNaturamtransfcrialiamapivinaNatura,Dcumn(^„.
ncquccnimaliudincrcatumNatura:Niimcn,autinptoducendJsautinconfer
vandisExpanfeliujusMachinzIndividuis,agnofcifaseft,pri«:rerSpirituiiil|i
,'n,DiviniOpificis,quipiimisaquisincubuit3^confiifainCliaorerurafeinijii
dcpotcntiamAauracduxit.cduaapctconaantcmaltcrationisRotaraveifi^s
coinponendo&rdolvcndohzcmfaioraGcomctricetraaat. t'
The text on this page is estimated to be only 9.77%
accurate
v.7.EtfccitDcus Firmamcntunijdivifitquca quas, qua: cr.int
Tub Firmamemo.ab his qux eraa fupcr Firmamentum. Et faftumcftita.
V. S Voc;tvicque Dcus Firmamenrum commi. Uyii ipfcdiiiii, & farta
funt. D«n. 3, t/. f 9- tfo.' Bencdicirc Cccli Dommo
LaudatcScSuperexalMieEum m lccula.Bcncdiciti Aqux omnes.quz
fupcr Ca;losfunt,DoiniiioA JLaudaicium m fcculii. qua: fub ccelo
funtinlocumunum;&3pp3[cat aii da.Etfaauiiycftita. V. 10.
EivocavitDeus3rid3m,tcriam,congrega. lioncfquc aquaium appellavtt
Maiia. .Et yidit Dcus quod clTet bonum. V. 1 1 . Et ait. Gcrminct terr.i
herbam vircnt tKLcnrcmrenun . ^clignumpomircium . I
r.uctam.iuxogenmibum.cuiusrcmcnmfemeupfo upcfterr.iin. Et
fjaumcftiU. '. li.Eiprotulit teiralKrbain viremem.&fi. iKcm femcn juxta
gcnus fuuin , lignumquc faci ftuftum & habens unumquodquc
fcmentcm , fe cundum fpccicm fuam, £t vidit Dcus quod eirei ■V. ij.
EiFaflumeft ?f»L\ 04v^ iperbafinfu.K foducisfocHui ■q, ru.id.irti Dom
ficct Cor Homuiii. llt c:.bibtet f.ic.cm 1 anijCor Hominisconfiimcc.
S.iturabai Campt&CcdriLibaniquas plantavii.
'Grt.r.VT4:BIxrtauHrtiD(U5:f:anitum! ia inFirmamcnco ca;li,& dividant
dicmac Vein:5t (Jnt in fign.i ac i:cmpora& dies ecani V. If. Ih Lutcant
in Firmamcntocah, & .Imnincm tcrram. Et fidum eftita. V. itf.Fccitq,
Dcusdiio Lummana ir V. 1 9. Et fjflum «ft vefpcre tc i Syr^l-f.r.
fcq.AltituJlni. Firm.i iilcntudo Ejm cfl, Spccics .-a-h ■lori,,;. Sol
OMcniDicmanuuncM imcllAliiinm.,M.i-n,>s..'f[a->omu t ipfum jc
mandjvrt fdhi..iic (JiiiUi ,1 in omni Mimdo lucet . iiucmno, C(K;i.v'ia.
ISixitctiamPeus, pr6'Juei«t! '^(«.i/W-iH.^ixltquaqueTScus.-
pTDancKwn» aqua reptilc anims vivcntis , 6c volatilc fuper ariimsm
vivcnttm in gcneie fuo.jumcta. & icptdi.% n fub firmamcnto cali. &
beftias tcto-feeundO fpceics fuas.Faaumq, cft ica.' j.Creavitquc Dcus
cctc grandia, & o j v.ij-,EtfccitDcu;b(fti.is tcrrx)U.\;ta fpecicsfuas, 1
ancm.im vivcntcm aiquc motabiltm .liumcnta &omnCicptiletcm
mgcntrcfuo. Et vipioduxci.int aqua: in rpcc Dcusquodcirec bonum. v.
2z. Bciiedixicque eis , dicci iulciplicamini,&ieplctc Aqua
ucmultipliafunccuo V^crbo, TunVoluntatcatquePoccntia.
Exunamairaconfulacrcatafuiuomniaquxmmchinc. ScdAntcacanquam
CrcacorcrasinGIoria.NuncquoqucEs&Erisproculdubio. Animxquc
purific.-itJEfurfumadTuamBcatitudinemvenient. fJOC
Principiumunumcflc potcftadDcclarationemnoftriBencdnfliLapidis.
N.imquem.-idmodumcxunamaflhcrc.itafuntomnia .
ficinno(trapraclicahocii?fumcfl"edcbcc ; Namomni.-i
noftrafccretacxUnaorinncurlmaginc.
InUbrisphilolbphorumiicuilubccvidcrc/noftcrLnpisappcUaturMicrocolm
us, Uuus &: Ttm'J5, M.ngneliaatquc etiamSuIphur &: Mcrcurjus d
Natura proportionaius. c
The text on this page is estimated to be only 0.00%
accurate
K ■.
The text on this page is estimated to be only 14.74%
accurate
V£RB0D0MINlFlRMATiSuNTCoEii,ETSpimTu0RisE)ns0MNi..-;.
.iK.;i.u5£oRUM,ri;iIm.;;. Spiritus DoMiNi REPirviT OrbemTerrarum:
OmniaSatiantu» BONITATE
TuADoMIN£:AVEll.TENTETEFACIEM,TuB.BANTUR:AuFFERsSl'IRITUM
EoRUM,ETDeFICmNTET In PuLV ER EM SuuM Re V ERTUNIUR
:EmITT1S SriRlTUM TuumEtCreantur:Sic RENOVAsFACiEMTERRii :
Gloria TuaIn Seculum. Pfalm.104. _ _ . , r- r /r /^ SMARACDINA
HERMETlSTABrLA. -r
Ttram,hncmcndacio,Ccrtum&vcnUiumm:Qiiode(linferius,e(lficutquode
ftSuneriu5,&guodc(lSuperiuscftllcucquodcft:nfcriusaJnerpctrandarai«
^^^ Y
C"'n"bUno,mcditationeUniu5:SicomnesRcsnaMtuerunrabliacUnaReAd.
iptarionc. Pater EjuseftSoi.MaterEjusLuna. Porravitillud Vcntusin
Vcntrcfuo. NutrixcjusTcrracft.Patir omnisTelefmitociusmundiefthic.
Vise|usintegracll,nvcrfafucritintcrram.
ScparabisTcrtamabIgne,fubtilcafpiiro,(uavircrcumma?iioingenio.
AfccnditaTcrrainCffilum.irerumquedefcendiiinTcrram,ErredpitVimSupei
iorum&;Infcriotum. SicliabcsGIoriamtotiusMundi. lde6fu.Ticta
teomnisoblcuritas.
Hiccfltotiusforritudinisfortitudoforris,quiavincctomucmrcmfubtilem,
omncmqucfolidampcxrrabiriSIC MUNDUS CREATUS EST.
HmcenmiAdaptaiioncsmirabilcs, quarummodusliiceft. Iraquc vocacus
fum Hccmes Ttifmegirtus, habens Trcspai:; tcs Philofophia: totius
Mundi. Complctum ert quod dixi dc Opcritione Solis. c
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookname.com