Python For Matlab Development Extend Matlab With 300000 Modules From The Python Package Index 1st Ed Danial download
Python For Matlab Development Extend Matlab With 300000 Modules From The Python Package Index 1st Ed Danial download
https://ebookbell.com/product/python-for-matlab-development-
extend-matlab-with-300000-modules-from-the-python-package-
index-1st-ed-danial-38662504
Dynamic System Modeling And Analysis With Matlab And Python For
Control Engineers Jongrae Kim
https://ebookbell.com/product/dynamic-system-modeling-and-analysis-
with-matlab-and-python-for-control-engineers-jongrae-kim-46431456
https://ebookbell.com/product/computational-framework-for-the-finite-
element-method-in-matlab-and-python-pavel-sumets-43875848
https://ebookbell.com/product/computational-framework-for-the-finite-
element-method-in-matlab-and-python-pavel-sumets-43892942
https://ebookbell.com/product/python-for-programmers-oswald-
campesato-45333572
Python For Data Analysis 3rd Wes Mckinney
https://ebookbell.com/product/python-for-data-analysis-3rd-wes-
mckinney-46540276
https://ebookbell.com/product/python-for-engineers-and-scientists-
rakesh-nayak-nishu-gupta-46814830
https://ebookbell.com/product/python-for-engineers-and-scientists-
concepts-and-applications-rakesh-nayak-46844500
Python For Cybersecurity Using Python For Cyber Offense And Defense
Howard E Poston Iii
https://ebookbell.com/product/python-for-cybersecurity-using-python-
for-cyber-offense-and-defense-howard-e-poston-iii-46873132
Python For Probability Statistics And Machine Learning 3rd Edition 3rd
Edition Jos Unpingco
https://ebookbell.com/product/python-for-probability-statistics-and-
machine-learning-3rd-edition-3rd-edition-jos-unpingco-47165906
Python for
MATLAB
Development
Extend MATLAB with 300,000+
Modules from the Python Package Index
—
Albert Danial
Python for MATLAB
Development
Extend MATLAB with 300,000+
Modules from the Python
Package Index
Albert Danial
Python for MATLAB Development: Extend MATLAB with 300,000+ Modules from the
Python Package Index
Albert Danial
Redondo Beach, CA, USA
Acknowledgments�����������������������������������������������������������������������������������������������xxvii
Chapter 1: Introduction�������������������������������������������������������������������������������������������� 1
1.1 Learn Python Through MATLAB Equivalents��������������������������������������������������������������������������� 2
1.2 Is Python Really Free?������������������������������������������������������������������������������������������������������������� 4
1.3 What About Toolboxes?����������������������������������������������������������������������������������������������������������� 5
1.4 Why Python Won’t Replace MATLAB��������������������������������������������������������������������������������������� 5
1.5 Contents at a Glance��������������������������������������������������������������������������������������������������������������� 6
1.6 I Already Know Python. How Do I Call Python Functions in MATLAB?������������������������������������� 8
1.7 The Recipes Don’t Work! MATLAB Crashes! (and What to Do About It)����������������������������������� 8
Chapter 2: Installation�������������������������������������������������������������������������������������������� 11
2.1 Downloads���������������������������������������������������������������������������������������������������������������������������� 11
2.1.1 Match Your Python and MATLAB Versions!������������������������������������������������������������������� 12
2.1.2 Verify That Python Runs������������������������������������������������������������������������������������������������ 12
2.2 Post-Install Configuration and Checkout������������������������������������������������������������������������������� 12
2.3 Creating and Running a Python Program������������������������������������������������������������������������������ 14
2.4 The Curse of Choice�������������������������������������������������������������������������������������������������������������� 15
2.5 V irtual Environments������������������������������������������������������������������������������������������������������������� 15
2.5.1 matpy, the Virtual Environment Used in This Book������������������������������������������������������� 16
2.5.2 Commands to Manage Virtual Environments���������������������������������������������������������������� 17
2.5.3 Keeping Your Virtual Environment Current������������������������������������������������������������������� 18
v
Table of Contents
vi
Table of Contents
3.8.4 Decorators�������������������������������������������������������������������������������������������������������������������� 46
3.8.5 Type Annotation and Argument Validation�������������������������������������������������������������������� 47
3.8.6 Left-Hand Side Argument Count����������������������������������������������������������������������������������� 49
3.9 Generators���������������������������������������������������������������������������������������������������������������������������� 50
3.9.1 y ield, next()������������������������������������������������������������������������������������������������������������������� 50
3.9.2 r ange()�������������������������������������������������������������������������������������������������������������������������� 51
3.10 Scoping Rules and Global Variables������������������������������������������������������������������������������������ 52
3.11 C
omments��������������������������������������������������������������������������������������������������������������������������� 54
3.11.1 D
ocstrings������������������������������������������������������������������������������������������������������������������ 54
3.12 L ine Continuation���������������������������������������������������������������������������������������������������������������� 56
3.13 E xceptions��������������������������������������������������������������������������������������������������������������������������� 56
3.14 Modules and Packages������������������������������������������������������������������������������������������������������� 58
3.14.1 N
amespace����������������������������������������������������������������������������������������������������������������� 58
3.14.2 d ef main()������������������������������������������������������������������������������������������������������������������� 60
3.14.3 Module Search Path��������������������������������������������������������������������������������������������������� 61
3.14.4 Installing New Modules���������������������������������������������������������������������������������������������� 62
3.14.5 Module Dependency Conflicts and Virtual Environments������������������������������������������� 63
vii
Table of Contents
viii
Table of Contents
6.5 Create Python Variables and Call Python Functions in MATLAB������������������������������������������ 161
6.5.1 Scalars������������������������������������������������������������������������������������������������������������������������ 161
6.5.2 Lists and Cell Arrays��������������������������������������������������������������������������������������������������� 163
6.5.3 Tuples������������������������������������������������������������������������������������������������������������������������� 165
6.5.4 Numeric Arrays����������������������������������������������������������������������������������������������������������� 166
6.5.5 Dictionaries and Structs��������������������������������������������������������������������������������������������� 168
6.5.6 Keyword Arguments��������������������������������������������������������������������������������������������������� 171
6.5.7 Python-to-MATLAB and MATLAB-to-Python Variable Converters������������������������������� 172
6.5.8 Traversing Generators������������������������������������������������������������������������������������������������� 172
6.5.9 Traversing zip()����������������������������������������������������������������������������������������������������������� 174
6.6 Modifying the Python Search Path Within MATLAB������������������������������������������������������������� 174
6.6.1 Extending sys.path with an Alias�������������������������������������������������������������������������������� 175
6.6.2 Extending sys.path with insert()��������������������������������������������������������������������������������� 175
6.6.3 Extending sys.path with append()������������������������������������������������������������������������������ 176
6.7 Python Bridge Modules������������������������������������������������������������������������������������������������������� 177
6.8 Debugging Python Code Called by MATLAB������������������������������������������������������������������������ 178
6.9 Summary of Steps to Calling Python Code from MATLAB��������������������������������������������������� 181
6.10 Call MATLAB from Python������������������������������������������������������������������������������������������������� 182
6.10.1 I nstall matlab.engine������������������������������������������������������������������������������������������������ 182
6.10.2 Call Functions in a New MATLAB Session���������������������������������������������������������������� 183
6.10.3 Call Functions in an Existing MATLAB Session��������������������������������������������������������� 184
6.11 Other Mechanisms for MATLAB/Python Interaction���������������������������������������������������������� 186
6.11.1 System Calls and File I/O������������������������������������������������������������������������������������������ 186
6.11.2 T CP/IP Exchange������������������������������������������������������������������������������������������������������� 188
x
Table of Contents
xi
Table of Contents
xii
Table of Contents
Chapter 9: Interacting with the Operating System and External Executables������ 315
9.1 Reading, Setting Environment Variables����������������������������������������������������������������������������� 315
9.2 Calling External Executables���������������������������������������������������������������������������������������������� 317
9.2.1 Checking for Failures�������������������������������������������������������������������������������������������������� 319
9.2.2 A Bytes-Like Object Is Required��������������������������������������������������������������������������������� 321
9.3 Inspecting the Process Table and Process Resources�������������������������������������������������������� 322
xiii
Table of Contents
xiv
Table of Contents
xv
Table of Contents
xvi
Table of Contents
xvii
Table of Contents
xviii
Table of Contents
14.14 Recipe 14-2: Accelerating MATLAB with Python on Multiple Computers������������������������ 646
14.14.1 Parallel Prime Sums with MATLAB������������������������������������������������������������������������� 647
14.14.2 Parallel Gigapixel Mandelbrot with MATLAB����������������������������������������������������������� 648
14.14.3 Parallel Direct Frequency Response with MATLAB������������������������������������������������� 652
14.15 References���������������������������������������������������������������������������������������������������������������������� 654
Index��������������������������������������������������������������������������������������������������������������������� 687
xix
About the Author
Albert Danial is an aerospace engineer with 30 years of
experience, currently working for Northrop Grumman near
Los Angeles. Before Northrop Grumman, he was a member
of the NASTRAN Numerical Methods team at MSC Software
and a systems analyst at SPARTA. He has a Bachelor of
Aerospace Engineering degree from the Georgia Institute of
Technology and master’s and Ph.D. degrees in Aeronautics
and Astronautics from Purdue University. He is the author of
cloc, the open source code counter.
Al has used MATLAB since 1990 and Python since 2006
Logan Delancey Studio for algorithm prototyping, earth science data processing,
spacecraft mission planning, optimization, visualization,
and countless utilities that simplify daily engineering work.
xxi
About the Technical Reviewers
Darrell Yocom earned a master’s degree in Computer
Science from USC and has over 40 years of experience
programming in the aerospace industry. Through the
years, he’s seen programming change from the monolithic
spaghetti-Fortran programs of the 1970s to today’s object-
oriented approaches. Darrell is an avid sailor and sails the
Pacific weekly on his sailboat, Stargazer.
xxiii
Preface
In 2018, I was chatting with a young engineer who had recently earned an engineering
master’s degree. MATLAB came up and she spoke of her frustration with license
shortages when projects came due at school. I had the same frustrations—25 years
earlier. Had nothing changed?
Of course, a lot had changed.
By then, we had already found our separate ways to Python to do the kind of work we
used to do in MATLAB. Why were so few MATLAB users aware of the power and freedom
Python could bring them?
I began assembling notes comparing Python solutions to their MATLAB equivalents
and shortly afterward learned of MATLAB’s py module. A binary API to Python?! Too
good to be true. It was too good to be true, in a sense; early versions couldn’t use critical
modules such as NumPy.
The MathWorks improved py with each MATLAB release, though, and today
MATLAB can run code from NumPy, SciPy, Pandas, matplotlib, statsmodels, dask,
even modules compiled with Cython, Numba, Pythran, and f2py. The MATLAB +
Python combination offers astounding possibilities to both languages, yet few MATLAB
developers know of this capability or how to take advantage of it. Fertile ground for a
new book, I thought.
xxv
Acknowledgments
Rachel Rybarczyk’s comments about MATLAB and Python inspired me to start the
journey that led to this book.
Alain Sei, although bowing out as my coauthor after realizing the magnitude of the
work ahead, nonetheless stayed on as my first reader. At our weekly meetings in building
R2, Alain put thought-provoking spin on things to keep my perspective fresh.
Rocco Samuele helped elevate the literary quality of the text. While I don’t have
Rocco’s chops for the written word, his edit suggestions clarified my writing.
Ravi Narasimhan’s critique of an early draft felt more like a mugging than a
review. After the bruises faded, it was clear he’d given me a goldmine of improvement
suggestions. Implementing them led to a more balanced tone and more convincing
assertions. Ravi also provided the MATLAB examples for the point and line plots on
maps shown in Section 12.4.
When Curtis Webb first told me about Numba four years ago, I dismissed his claims
that it could make Python functions run 10 ×, even 30 × faster—without using a C/C++/
Fortran compiler. Impossible! Yet somehow, like a magical alien technology, Numba
does just that. Best tip ever, thanks, Curtis!
Parker Hudnut gave valuable “big picture” suggestions on the book’s overall
structure. Thanks! The beer’s on me the next time we’re at building H.
Thank you Steven Millett, Petra Poschmann, Drew Swalley, and Mark Vaughn for tips
on missing or incomplete topics.
Thanks to Professor John Hedengren for letting me copy his predband() function in
my section on prediction intervals (Section 11.7.3). His website1 has excellent videos on
statistical computations in Python.
Thanks to Professor James Doyle for advice on, and a technical review of, the
frequency response section, Section 14.13.7. His classic “red book” on structural wave
propagation [1] remains one of my favorite technical reads.
1
https://apmonitor.com/che263/index.php/Main/PythonRegressionStatistics
xxvii
Acknowledgments
xxviii
CHAPTER 1
Introduction
MATLAB is amazing—but you already know this. With a few lines of code, you can load
data, manipulate it countless ways, view it, and extract its deeper meaning. MATLAB is
also a terrific sandbox for prototyping algorithms and exploring numerical experiments,
for simulating phenomena, for churning through test results, and for generating reports.
Additionally, MATLAB’s documentation and tutorials—either built-in, hosted at The
MathWorks’ website, or available on YouTube—are thorough and high quality.
The underdocumented and underappreciated MATLAB py module, however,
motivated the creation of this book. The py module provides a binary interface between
MATLAB and Python. That’s huge—it opens a door from MATLAB to hundreds of
thousands of open source Python packages for machine learning, artificial intelligence,
data mining, database access, astronometric computation, geographic information
services, web services, high performance computing, and countless others.
Better still, the power of Python via MATLAB’s py is available for free to individuals
and at low cost to corporations (see Section 1.2). There is a caveat though: to use py,
you must also know Python. This book aims to be your guide to learning Python and
taking full advantage of MATLAB’s ability to interact with it. When viewed as a MATLAB
extension, it can be said without exaggeration that
1
© Albert Danial 2022
A. Danial, Python for MATLAB Development, https://doi.org/10.1007/978-1-4842-7223-7_1
Chapter 1 Introduction
MATLAB: Python:
To keep the examples tight, I’ve edited them for brevity; the actual result from both
whos commands has more columns than are shown. MATLAB’s ans = line is also stripped
throughout.
Helpful too are the many function names Python’s numeric and scientific modules
share with their MATLAB counterparts. Table 1-1 shows a small subset of these. The
Python function prefixes np, npr, plt, and sci are defined with Python statements
import numpy as np, import numpy.random as npr, import matplotlib.pyplot as
plt, and import scipy.interpolate as sci.
2
Chapter 1 Introduction
3
Chapter 1 Introduction
While the similarities are encouraging, the two languages have fundamental
differences that will be most noticeable in Chapter 4.
4
Chapter 1 Introduction
1
Development on SimuPy at https://github.com/simupy/simupy, the closest Python project to
Simulink, has stagnated.
5
Chapter 1 Introduction
The MathWorks products are invaluable when you’re using them to solve the most
niche and technically specialized problems conveniently, thoroughly, and quickly.
Python can play a supporting role alongside MATLAB and Simulink but won’t be their
replacement.
Having said that, once you’re proficient with Python you’ll find you need MATLAB
less. That’s not so much an indictment against MATLAB as it is an endorsement of
Python. Python, being a general-purpose language, excels at many things MATLAB is
less suited for. Let Python take care of the “low-hanging fruit” tasks such as aggregating
data from a collection of NetCDF4 files, scanning a directory for Excel files having tabs
named “2017 inventory,” and reformatting plain text data into a set of JSON records.
Oddly, Python may also be the better choice at the other end of the spectrum for the
biggest and most computationally challenging jobs. Unlike MATLAB, Python’s parallel
processing modules such as Dask are not restricted by licenses, so you can run on as
many processors as you can access.
Knowing Python alongside MATLAB expands your problem-solving options.
Whether that means solving new problems with just Python or with MATLAB/Python
hybrids, you’ll have considerably more power at your command than you have with
MATLAB alone.
6
Chapter 1 Introduction
Chapter 6, “Call Python Functions from MATLAB,” begins the heart of this book. It
covers the basics of MATLAB’s py module, shows how to extend the Python search path
within MATLAB, describes the nuances of Python-native variables in MATLAB and how
to convert them to MATLAB-native variables, and shows other mechanisms for the two
languages to interact.
“Input and Output,” Chapter 7, covers reading and writing text and binary files
common to numeric work: plain text, JSON, YAML, XML, CSV, Excel, raw binary, HDF5,
netCDF. The section on network I/O shows how to write TCP/IP clients and servers
in both Python and MATLAB. The first simple MATLAB-calling-Python recipes (to let
MATLAB read YAML and .ini files) appear in this chapter.
In addition to reading and writing files, programs must sometimes read directory
contents, search for files, get file metadata like size and modification time, and remove
directories. These actions are covered in Chapter 8, “Interacting with the File System.”
Python and MATLAB occasionally need to run external executables, check
environment variables, and monitor the computer’s load. Chapter 9, “Interacting with
the Operating System and External Executables,” shows how this is done in the two
languages.
Chapter 10, “Object-Oriented Programming,” shows how classes are defined and
instantiated in MATLAB and Python.
Chapter 11, “NumPy and SciPy,” spans nearly a quarter of this book. It covers
NumPy’s ndarray, the Python object closest to MATLAB’s matrix, as well as the many
functions that perform array operations, linear algebra, and interpolation. SciPy, a
scientific computing package built on NumPy, brings additional capability such as
sparse matrices, optimization, curve fitting, and differential equation solvers.
Data visualization is covered in Chapter 12, “Plotting.” In addition to the basics of
point, line, and contour plots, overlaying data on maps is also described.
The Pandas module for Python appeared five years before The MathWorks added
tables to MATLAB. Chapter 13, “Tables and Dataframes,” shows the basics of Pandas
dataframes and how equivalent operations are done with MATLAB tables.
Chapter 14, “High Performance Computing,” explores ways to make Python run
faster—and faster Python can mean faster MATLAB programs if you’re willing to
implement slow MATLAB functions in Python. The chapter has examples of using
Cython, Pythran, f2py, and Numba to make Python run faster on a single computer, and
dask to run Python on clusters. You’ll see that wherever a Python program is accelerated,
the analogous MATLAB program can also be accelerated the same amount just by
having MATLAB call faster Python functions.
7
Chapter 1 Introduction
MATLAB and Python both have sharp edges that can bring grief to new developers.
Chapter 15, “Language Pitfalls,” covers aspects of the two languages to watch out for.
Appendix A lists all MATLAB-calling-Python recipes in this book while appendices
B-E contain source listings that are too long for the body of the book. All source code
from the book can be found at the book’s Github repository at https://github.com/
Apress/python-for-matlab-development.
8
Chapter 1 Introduction
The best MATLAB-friendly environment I’ve been able to devise is the matpy virtual
environment described in Section 2.5.1. matpy cannot prevent all MATLAB crashes.
An example is loading Python’s matplotlib module into MATLAB, then making a plot
using matplotlib's default Qt backend. MATLAB crashes as soon as the plot command
is called:
MATLAB 2020b:
9
CHAPTER 2
Installation
Installing MATLAB is pretty straightforward: download the installation package
from the MathWorks’ website, run the installer, then either authenticate with your
MathWorks credentials or provide licensing information. Installing Python is equally
easy on Windows and Linux, but installing the recommended Anaconda distribution on
macOS is more involved because it requires one to also install the Xcode development
environment. Finally, configuring a Python installation that MATLAB can use
seamlessly is harder still. In this chapter, I’ll cover installation steps, explain why
Python configuration is more problematic than MATLAB, then show how to create an
installation that can run the examples in this book.
2.1 Downloads
Python installers for macOS and Windows are freely available from python.org. Linux
and macOS distributions generally come with Python preinstalled.
It is best to avoid using a Python installation that comes with your operating
system, however. If you install new modules or upgrade existing ones, you might
break functionality your OS relies on. You are best off leaving the OS-provided Python
version alone.
Regardless of your computer’s operating system, my recommendation is to
download and install the Anaconda Python distribution from anaconda.com. Unless you
are making one installation for multiple people, install it into a directory or folder that
you own. Unlike the “vanilla” Python installer from python.org, Anaconda comes with
NumPy, SciPy, matplotlib, Pandas, and many other modules of interest to scientists and
engineers. Anaconda also includes the Spyder IDE, which, while not as capable as the
MATLAB IDE, has useful editing, debugging, and profiling options. Spyder even includes
a MATLAB theme.
11
© Albert Danial 2022
A. Danial, Python for MATLAB Development, https://doi.org/10.1007/978-1-4842-7223-7_2
Chapter 2 Installation
The result should show Python 3.8.8—or higher, if your MATLAB version supports
newer releases.
1
www.mathworks.com/help/matlab/matlab_external/install-supported-python-
implementation.html
2
https://repo.anaconda.com/archive/
12
Chapter 2 Installation
The correct update commands for these particular installations are therefore
Linux:
and
Windows:
After the update, run ipython either from the command line on Linux and macOS or
an Anaconda Prompt terminal on Windows to start a read-evaluate-print-loop (REPL)
similar to MATLAB’s console-like interactive environment.
Our first step will be to make a simple variable assignment and then invoke the whos
command to see what’s in your environment:
MATLAB: Python:
>> a = 1; In : a = 1
>> whos In : whos
Name Size Bytes Class Variable Type Data/Info
a 1x1 8 double ----------------------------
a int 1
13
Chapter 2 Installation
When they are invoked as commands, Unix-like operating systems examine the first
line of executable text files for the characters #!—the pound-bang, or shebang. If these
exist, the operating system invokes the rest of the first line to interpret the remaining
lines in the file. Examples are
#!/usr/bin/env python3
#!/usr/bin/python3
#!/apps/python/3.8.8/bin/python
The first of these runs the env command to select the first python3 executable in your
$PATH. Doing so is considered a best practice.
Pound-bang lines are ignored on Windows.
Interestingly, the path to the MATLAB executable can also be used on the pound-
bang line to run MATLAB code as a stand-alone batch script:
Windows 10:
16
Chapter 2 Installation
The MATLAB command must be started from a terminal session which has matpy
activated, for example:
console:
3
https://conda.io/projects/conda/en/latest/user-guide/tasks/
manage-environments.html
17
Chapter 2 Installation
conda deactivate
18
Chapter 2 Installation
However, don’t do this yet! Our matpy conda environment was created with pinned
versions of modules whose shared libraries need to be consistent with their MATLAB
counterparts. Without taking precautions, update --all may install newer versions of
shared libraries that cause MATLAB to fail when it runs Python code.
The necessary precaution requires adding a file called pinned in the relevant conda
environment’s conda-meta directory. Where is this directory? Output from conda info
will tell you the location. conda-meta is in the directory shown for active env location.
For example:
console:
active environment : matpy
active env location : /usr/local/anaconda3/2020.07/envs/matpy
shell level : 2
user config file : /home/al/.condarc
..lines deleted..
python=3.8.*
intel-openmp=2021.2.*
llvm-openmp=10.0.*
libllvm10=10.0.*
llvmlite=0.36.*
The asterisks in the third numeric position means any value may be used. It’s safe to
run conda update --all after this file is in place.
Note conda environments like matpy are easy to create, modify, experiment
with, and destroy. Once you have an environment you want to keep for a while,
remember to add a pinned file before you update it.
19
Chapter 2 Installation
> ipython
In : import numpy
In : import matplotlib.pyplot
In : import scipy.interpolate
In : import pandas
In : import statsmodels
In : import h5py
In : import dask
We’ll use many additional modules, but if these import without errors, your
installation will be sufficient for rigorous numerical analysis.
20
Chapter 2 Installation
ipython has a similar mechanism to run commands at the start of each session. This
is even more necessary in Python than MATLAB because most Python sessions begin
with module imports that should be done every time; importing these automatically is a
terrific convenience. First identify the ipython “profile” directory:
In : import IPython
In : IPython.paths.locate_profile()
Out: '/home/al/.ipython/profile_default'
ipython start-up commands can be added to any file ending with .py in the startup
directory below the profile directory. If multiple .py files exist there, they are executed in
alphabetical order. I’ve customized my ipython start-up with the file
/home/al/.ipython/profile_default/startup/00-start.py
which contains
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import plot, show, scatter, imshow, figure, savefig
21
CHAPTER 3
Language Basics
The fundamental elements of the Python language—variable assignment, indentation,
array indexing, for and while loops, if statements, functions, comments, exceptions,
modules—are covered in this chapter. Although classes and object-oriented
programming are also fundamental aspects of Python, these will be covered in
Chapter 10.
3.1 Assignment
Python supports four forms of variable assignment: conventional, conditional, in-place,
and the recently added “walrus operator.”
MATLAB: Python:
The semicolon at the end of each MATLAB line is optional. Without it, MATLAB
prints the contents of the variable to STDOUT—helpful for observing values during
development but distracting for working code.
23
© Albert Danial 2022
A. Danial, Python for MATLAB Development, https://doi.org/10.1007/978-1-4842-7223-7_3
Chapter 3 Language Basics
MATLAB: Python:
Python also supports chained assignment where all variables are set to the
same value:
Python:
In : f = g = 5.5
In : f
Out: 5.5
In : g
Out: 5.5
In : g = 7
In : h = 'bigger than 5' if g > 5 else 'smaller'
In : h
Out: 'bigger than 5'
In : g = -7
In : h = 'bigger than 5' if g > 5 else 'smaller'
In : h
Out: 'smaller'
24
Chapter 3 Language Basics
MATLAB: Python:
>> a = 0; In : a = 0
>> a = a + 1 In : a += 1
a = 1 In : a
Out: 1
+= x Increment by x
-= x Decrement by x
*= x Multiply by x
/= x Divide by x
**= x Raise to the x power
|= x Bitwise OR with x
&= x Bitwise AND with x
^= x Bitwise exclusive OR with x
<<= x Bit shift left x times
>>= x Bit shift right x times
Of course, MATLAB can perform these operations too, just not in-place.
25
Chapter 3 Language Basics
In : x := 100
In : x
Out: 100
Nothing surprising here; x was set to 100. What’s not obvious is that the entire
statement x := 100 also has the value of 100. We can see that if we capture the full
expression with another variable:
Python:
In : y = (x := 100)
In : x
Out: 100
In : y
Out: 100
One practical use of this behavior is inserting intermediate variables in the middle
of a computation for use later. Here’s the Pythagorean theorem equation with additional
variables inserted to store intermediate values of Δx and Δy:
Python:
26
Chapter 3 Language Basics
In : dx
Out: 7.58
In : dy
Out: -31.37
Inserting dx := and dy := lets us save these intermediate values without disrupting the
larger computation for d.
The walrus operator is also convenient when working with regular expressions (to be
covered in Section 4.2.6) as it allows one to populate a match object and test whether or
not it was successful in a single step:
import re import re
L = "n= Bob" L = "n= Bob"
m = re.search(r"n=\s*(\w+)", L) if m := re.search(r"n=\s*(\w+)", L):
if m is not None: print('name is ',m.group(1))
print('name is ',m.group(1))
3.2 Printing
In the MATLAB IDE and .m files, the results of an expression are printed immediately
unless the line ends with a semicolon. A Python REPL such as ipython will also print
expressions that have no assignment, that is, without an equals sign:
MATLAB: Python:
>> i = 1 In : i = 1
i = 1 In : i
>> i, length('abc') Out: 1
i = 1 In : i, len('abc')
ans = 3 Out: (1, 3)
27
Chapter 3 Language Basics
Similarly, within a MATLAB .m file, the result of every assignment is printed unless
the line ends with a semicolon. Python follows more typical programming conventions
and requires a call to its print() function to display output from a running .py file.
MATLAB’s fprintf() function is a close analog to Python’s print() and provides similar
capability to displaying formatted text. There are a few notable difference between the
two, though.
Python’s print():
String formatting in Python is covered in detail in Section 4.2.3; these few lines give a
quick preview of equivalent string and floating-point output formatting:
MATLAB: Python:
3.3 Indentation
A Python hallmark is its use of indentation to define the scope of classes, functions,
loops, if statements, exception handlers, and so on. Interestingly, code written in other
computer languages that ignore leading whitespace generally end up with similar
indentation because this makes code easier to understand and is considered good
coding style.
28
Another Random Scribd Document
with Unrelated Content
"Only the morality of business," put in a coarse-looking fellow
who, having been betwixt and between the conversations, had been
drinking rather heavily. "There's no need for you to join the ladies as
yet, Mrs. Gissing."
Major Erlton, at her right hand, scowled, and the boy on her left
flushed up to the eyes. He was her latest admirer, and was still in
the stage when she seemed an angel incarnate. Only the day before
he had wanted to call out a cynical senior who had answered his
vehement wonder as to how a woman like she was could have
married a little beast like Gissing, with the irreverent suggestion that
it might be because the name rhymed with kissing.
In the present instance she heeded neither the scowl nor the
flush, and her voice came calmly. "I don't intend to, doctor. I mean
to send you into the drawing room instead. That will be quite as
effectual to the proprieties."
A sudden dull red showed on the face whose admiration Alice was
answering by a smile.
"I won a lot, also," she interrupted hastily, "thanks to your tip,
Erlton. You never forget your friends."
"I'll remember you the next time if you like, Mainwaring," he said,
"but someone has to lose in every game. I'd grasped that fact before
I was your age, and made up my mind it shouldn't be me."
The room was heavy with the odors of meats and drinks. Dark as
it was, the flood of sunshine streaming into the veranda outside,
where yellow hornets were buzzing and the servants washing up the
dishes, sent a glare even into the shadows. Neither the furniture nor
appointments of the room owed anything to the East--for Indian art
was, so to speak, not as yet invented for English folk--yet there was
a strange unkennedness about their would-be familiarity which
suddenly struck the latest exile, young Mainwaring.
She came to a stand in front of him like a child, her hands behind
her back, but her china-blue eyes had a world of shrewdness in
them. "Don't I? Do you think I care for men either? I don't. You just
amuse me, and I've got to be amused. By the way, did you
remember to order the cart at five sharp? I want to go round the
Fair before the Club."
If they had been married ten times over, their spending the
afternoon together could not have been more of a foregone
conclusion; there seemed, indeed, no choice in the matter. And they
were prosaically punctual, too; at "five sharp" they climbed into the
high dog-cart boldly, in face of a whole posse of servants dressed in
the nabob and pagoda-tree style, also with silver crests in their pith
turbans and huge monograms on their breastplates; old-fashioned
servants with the most antiquated notions as to the needs of the
sahib logue, and a fund of passive resentment for the least change
in the inherited routine of service. Changes which they referred to
the fact that the new-fangled sahibs were not real sahibs. But the
heavy, little and big breakfasts, the unlimited beer, the solid dinners,
the milk punch and brandy pâni, all had their appointed values in the
Gissings' house; so the servants watched their mistress with
approving smiles. And on Mondays there was always a larger posse
than usual to see the old Mai, who had been Alice Gissing's ayah for
years and years, hand up the bouquet which the gardener always
had ready, and say, "My salaams to the missy-baba." Mrs. Gissing
used to take the flowers just as she took her parasol or her gloves.
Then she would say, "All right," partly to the ayah, partly to her
cavalier, and the dog-cart, or buggy, or mail-phaeton, whichever it
happened to be, would go spinning away. For the old Mai had
handed the flowers into many different turn-outs and remained on
the steps ready with the authority of age and long service, to crush
any frivolous remarks newcomers might make. But the destination of
the bouquet was always the same; and that was to stand in a peg
tumbler at the foot of a tiny white marble cross in the cemetery. Mrs.
Gissing put a fresh offering in it every Monday, going through the
ceremony with a placid interest; for the date on the cross was far
back in the years. Still, she used to speak of the little life which had
come and gone from hers when she was yet a child herself, with a
certain self-possessed plaintiveness born of long habit.
"I was barely seventeen," she would say, "and it was a dear little
thing. Then Saumarez was transferred, and I never returned to
Lucknow till I married Gissing. It was odd, wasn't it, marrying twice
to the same station. But, of course, I can't ask him to come here, so
it is doubly kind of you; for I couldn't come alone, it is so sad."
Her blue eyes would be limpid with actual tears; yet as she waited
for the return of the tumbler, which the watchman always had to
wash out, she looked more like some dainty figure on a cracker than
a weeping Niobe. Nevertheless, the admirers whom she took in
succession into her confidence thought it sweet and womanly of her
never to have forgotten the dead baby, though they rather admired
her dislike to live ones. Some of them, when their part in the weekly
drama came upon them, as it always did in the first flush of their
fancy for the principal actress in it, began by being quite sentimental
over it. Herbert Erlton did. He went so far once as to bring an
additional bouquet of pansies from his wife's pet bed; but the little
lady had looked at it with plaintive distrust. "Pansies withered so
soon," she said, "and as the bouquet had to last a whole week,
something less fragile was better." Indeed, the gardener's bouquets,
compact, hard, with the blossoms all jammed into little spots of color
among the protruding sprigs of privet, were more suited to her calm
permanency of regret, than the passionate purple posy which had
looked so pathetically out of place in the big man's coarse hands.
She had taken it from him, however, and strewn the already
drooping flowers about the marble. They looked pretty, she had said,
though the others were best, as she liked everything to be tidy;
because she had been very, very fond of the poor little dear.
Saumarez had never been kind, and it had been so pretty; dark, like
its father, who had been a very handsome man. She had cried for
days, then, though she didn't like children now. But she would
always remember this one, always! The old Mai and she often talked
of it; especially when she was dressing for a ball, because the
gardener brought bouquets for them also.
"I've been wondering, Allie," he said, "what you would have been
like if that baby had lived. Would you have cared for it?"
Her eyes grew startled. "But I do care for it! Why should I come if
I didn't? It isn't amusing, I'm sure; so I think it very unkind of you to
suggest----"
She was pinning the buttonhole into his coat methodically, and he
could not refuse an answering smile; but the puzzled look remained.
"I suppose you do, or you wouldn't----" he began slowly. Then a
sudden emotion showed in face and voice. "You slip from me
somehow, Allie--slip like an eel. I never get a real hold---- Well! I
wonder if women understand themselves? They ought to, for
nobody else can, that's one comfort." Whether he meant he was no
denser than previous recipients of rosebuds, or that mankind
benefited by failing to grasp feminine standards, was not clear. And
Mrs. Gissing was more interested in the fact that the mare was
growing restive. So they climbed into the high dog-cart again, and
took her a quieting spin down the road. The fresh wind of their own
speed blew in their faces, the mare's feet scarcely seemed to touch
the ground, the trees slipped past quickly, the palm-squirrels fled
chirruping. He flicked his whip gayly at them in boyish fashion as he
sat well back, his big hand giving to the mare's mouth. Hers lay
equably in her lap, though the pace would have made most women
clutch at the rail.
"Jolly altogether; jolly as it can be," she replied with the frank
delight of a girl. They had forgotten themselves innocently enough;
but one of the men in a dog-cart, past which they had flashed, put
on an outraged expression.
"Erlton and Mrs. Gissing again!" he fussed. "I shall tell my wife to
cut her. Being in business ourselves we have tried to keep square.
But this is an open scandal. I wonder Mrs. Erlton puts up with it. I
wouldn't."
His companion shook his head. "Dangerous work, saying that.
Wait till you are a woman. I know more about them than most,
being a doctor, so I never venture on an opinion. But, honestly, I
believe most women--that little one ahead into the bargain--don't
care a button one way or the other. And, for all our talk, I don't
believe we do either, when all is said and done."
"Passion, Love, Lust, the attractions of sex for sex--what you will,"
said the doctor, breaking the silence. "Nothing is easier knocked out
of a man, if he is worth calling one--a bugle call, a tight corner----
God Almighty!--they're over that child! Drive on like the devil, man,
and let me see what I can do."
Then the doctor, who had been busy with deft but helpless hands,
rose from his knees, saying a word or two in Hindustani which
provoked a whining reply from the woman.
"She admits it was no one's fault," he said. "So Erlton, if you will
take our dog-cart----"
But the Major had faced the position by this time. "I can't go. She
is a camp follower, I expect, and I shall have to find out--for
compensation and all that. If you would take Mrs. Gissing----" His
voice, steady till then, broke perceptibly over the name; its owner
looked up sharply, and going over to him laid her hand on his arm.
"It wasn't your fault," she said, still in that odd hard voice. "You
had the mare in hand; she didn't stir an inch. It is a dreadful thing to
happen, but"--she threw her head back a little, her wide eyes
narrowed as a frown puckered her smooth forehead--"it isn't as if we
could have prevented it. The thing had to be."
She might have been the incarnation of Fate itself as she glanced
down at the dead child in the dust, at the living one reaching from
its mother's arms to touch its sister curiously, at the slow tears of
the mother herself as she acquiesced in the eternal fitness of things;
for a girl more or less was not much in the mud hovel, where she
and her man lived hardly, and the Huzoors would doubtless give
rupees in exchange, for they were just. She wept louder, however,
when with conventional wailing the women from the clustering huts
joined her, while the men, frankly curious, listened to the groom's
spirited description of the incident.
"You had better go, Allie; you do no good here," said the Major
almost roughly. He was anxious to get through with it all; he was
absorbed in it.
So the man who had said he was going to tell his wife to cut Mrs.
Gissing had to help her into the dog-cart.
"It was horrible, wasn't it?" she said suddenly when, in silence,
they had left the little tragedy far behind them. "We were going an
awful pace, but you saw he had the mare in hand. He is awfully
strong, you know." She paused, and a reflectively complacent smile
stole to her face. "I suppose you will think it horrid," she went on;
"but it doesn't feel to me like killing a human being, you know. I'm
sorry, of course, but I should have been much sorrier if it had been a
white baby. Wouldn't you?"
She set aside his evasion remorselessly. "I know all that! People
say, of course, that it is wicked not to feel the same toward people
whether they're black or white. But we don't. And they don't either.
They feel just the same about us because we are white. Don't you
think they do?"
"You had better drive round the back way to the Fair," she said
considerately. "Somebody there will take me off your hands.
Otherwise you will have to drive me to the Club; for I'm not going
home. It would be dreadful after that horrid business. Besides, the
Fair will cheer me up. One doesn't understand it, you know, and the
people crowd along like figures on a magic lantern slide. I mean that
you never know what's coming next, and that is always so jolly, isn't
it?"
It might be, but the man with the wife felt relieved when, five
minutes afterward, she transferred herself to young Mainwaring's
buggy. The boy, however, felt as if an angel had fluttered down from
the skies to the worn, broken-springed cushion beside him; an angel
to be guarded from humanity--even her own.
"How the beggars stare," he said after they had walked the horse
for a space through the surging crowds. "Let us get away from the
grinning apes." He would have liked to take her to paradise and put
flaming swords at the gate.
"They don't grin," she replied curtly, "they stare like Bank-holiday
people stare at the wild beasts in the Zoo. But let us get away from
the watered road, the policemen, and all that. That's no fun. See, go
down that turning into the middle of it; you can get out that way to
the river road afterward if you like."
The bribe was sufficient; it was not far across to peace and quiet,
so the turn was made. Nor was the staring worse in the irregular
lane of booths and stalls down which they drove. The unchecked
crowd was strangely silent despite the numberless children carried
shoulder high to see the show, and though the air was full of
throbbings of tomtoms, twanging of sutaras, intermittent poppings
and fizzings of squibs. But it was also strangely insistent; going on
its way regardless of the shouting groom.
"Take care," said Mrs. Gissing lightly, "don't run over another
child. By the way, I forgot to tell you--the Fair was so funny--but
Erlton ran over a black baby. It wasn't his fault a bit, and the mother,
luckily, didn't seem to mind; because it was a girl, I expect. Aren't
they an odd people? One really never knows what will make them
cry or laugh."
She was out of the dog-cart as she spoke despite his protest that
it was impossible--that she must not venture.
She was by this time in the thick of the crowd, which gave way
instinctively, and he could do nothing but follow; his boyish face
stern with the mere thought her idle words had conjured up. Do her
any injury? Her dainty dress should not even be touched if he could
help it.
"But I want to see what they're laughing at," she replied. And
then in perfect mimicry of the groom's familiar cry, her high clear
voice echoed over the heads in front of her: "Hut! Hut! Ari bhaiyan!
Hut!"
They turned to see her gay face full of smiles, joyous, confident,
sympathetic, and the next minute the cry was echoed with
approving grins from a dozen responsive throats.
There were quick hustlings to right and left, quick nods and
smiles, even broad laughs full of good fellowship; so that she found
herself at the innermost circle with clear view of the central space,
of the cause of the laughter. It made her give a faint gasp and stand
transfixed. Two white-masked figures, clasped waist to waist, were
waltzing about tipsily. One had a curled flaxen wig, a muslin dress
distended by an all too visible crinoline, giving full play to a pair of
prancing brown legs. The other wore an old staff uniform, cocked
hat and feather complete. The flaxen curls rested on the tarnished
epaulet, the unembracing arms flourished brandy bottles.
She turned like lightning to the sound, her cheeks for the first
time aflame, but she could see no one in the circle of dark faces
whom she could credit with the exclamation. Yet she felt sure she
had heard it.
"Him? who--what? Who said bravo?" asked the lad. He had been
too angry to notice the exclamation at the time.
Mrs. Gissing had guessed right. The man in the Afghan cap was
Jim Douglas, who found the disguise of a frontiersman the easiest to
assume, when, as now, he wanted to mix in a crowd. And he would
have said "Bravo" a dozen times over if he had thought the little lady
would like to hear it; for her quick denial of the possibility of insult
had roused his keenest admiration. Here had spoken a dignity he
had not expected to find in one whom he only knew as a woman
Major Erlton delighted to honor. A dignity lacking in the big brave
boy beside her; lacking, alas! in many a big brave Englishman of
greater importance. So he had risked detection by that sudden
"Bravo!" Not that he dreaded it much. To begin with, he was used to
it, even when he posed as an out-lander, for there was a trick in his
gait, not to be Orientalized, which made policemen salute gravely as
he passed disguised to the tent. Then there was ignorance of some
one or another of the million shibboleths which divide men from
each other in India; shibboleths too numerous for one lifetime's
learning, which require to be born in the blood, bred in the bone. In
this case, also, he had every intention of asserting his race by licking
one at least of the offenders when the show was over. For he
happened to know one of them; having indeed licked him a few days
before over a certain piece of bone. So, as the crowd, accepting the
finale of one amusement placidly, drifted away to see another, he
walked over to the tent in which the discomforted caricaturists had
found refuge. It was a tattered old military bell-tent, bought most
likely at some auction with the tattered old staff uniform. As he lifted
the flap the sound of escaping feet made him expect a stern chase;
but he was mistaken. Two figures rose with a start of studied
surprise and salaamed profoundly as he entered. They were both
stark naked save for a waistcloth, and Jim Douglas could not resist a
quick glance round for the discarded costumes. They were nowhere
to be seen; being hidden, probably, under the litter of properties
strewing the squalid green-room. Still of the identity of the man he
knew Jim Douglas had no doubt, and as this one was also the
nearest, he promptly seized him by the both shoulders and gave him
a sound Western kick, which would have been followed by others if
the recipient had not slipped from his hold like an eel. For Jhungi,
Bunjârah, and general vagrant, habitually oiled himself from head to
foot after the manner of his profession as a precaution against such
possible attempts at capture.
His assailant, grasping this fact, at any rate, did not risk dignity by
pursuit; though the man stood salaaming again within arm's length.
Jim Douglas without a word slipped his hand down the man's
back. The wales of a sound hiding were palpable; so was his wince
as he dodged aside to salaam again.
"But you can surely earn the stomachful honestly," he said, anger
passing into irritation. "What made you take to this trade?" He
kicked at a pile of properties, and in so doing disclosed the skeleton
of a crinoline. Jhungi with a shocked expression stooped down and
covered it up decorously.
Tiddu resumed the cracked voice and let the smile become visible,
and, as if by magic, the illusion disappeared. "The Huzoor is right.
We are wanderers. But in my youth a woman tied me to one place,
one face; women have the trick, Huzoor, even if they are wanderers
themselves. This one was, but I loved her; so after we had burned
her and her fellow-wanderer together hand-in-hand, according to
the custom, so that they might wander elsewhere but not in the
tribe, I lingered on. He was the father of Jhungi, and the boy being
left destitute I taught him to play; for it needs two in the play as in
life. The man and the woman, or folks care not for it. So I taught
Jhungi----"
A faint chuckle came from the veil. "And Bhungi. He plays well,
and hath beguiled an old rascal with thin legs and a fat face like
mine into playing with him. Some, even the Huzoor himself, might
be beguiled into mistaking Siddu for Tiddu. But it is a tom-cat to a
tiger. So being warned, the Huzoor will give no unearned blows. Yet
if he did, are not two kicks bearable from the mulch-cow?" As he
spoke he angled out a hand impudently for an alms with the
beggars' cry of "Alakh," to point his meaning.
Tiddu rose, let fall the veil to decent dignified drapery, and fixed
his eyes full on the questioner. They were luminous eyes, differing
from Jhungi's beady ones as the fire-opal differs from the diamond.
"The Huzoor thinks I lie; but he must have heard of the doctor
sahib in Calcutta who made suffering forget to suffer."
"You mean Dr. Easdale. Did you know him? Was he a pupil of
yours?" came the cynical question.
"How do you know I want to find out anything?" said the latter,
after a pause.
Tiddu laughed. "The Huzoor must find a turban heavy, and there
is no room for English toes in a native shoe; folk seek not such
discomfort for naught."
Jim Douglas paused again; the fellow was a charlatan, but he was
consummately clever; and if there was anything certain in this world
it was the wisdom of forgetting Western prejudices occasionally in
dealing with the East.
"Send that man away," he said curtly, "I want to talk to you
alone."
Jhungi, who all this time had been telling his beads like the best
of beggars, looked up with some perplexity; whether real or
assumed Jim Douglas felt it was impossible to say, in that hotbed of
deception.
"Bhungi?" echoed the former, rising to his feet. "Ay! that will I, if I
meet him. But God knows as to that. God knows of Bhungi----"
"Or Siddu's?"
"Or Siddu's," assented the mountebank calmly. "But the Huzoor
cannot learn to use his gift from that old rascal. He must come to
the many-faced one, who is ready to teach it."
"Why?"
Was it worth it? Jim Douglas decided instantly that it might be.
Not for the gift's sake; of that he was incredulous. But Tiddu was a
consummate actor and could teach many tricks worth knowing.
Then in this roving commission to report on anything he saw and
heard to the military magnate, it would suit him for the time to have
the service of an arrant scoundrel. Besides, the pay promised him
being but small, the wisdom of having a second string to the bow of
ambition had already decided him on combining inquiry with
judicious horse-dealing; since he could thus wander through villages
buying, through towns selling, without arousing suspicion; and this
life in a caravan would start him on these lines effectively. Finally,
this offer of Tiddu's was unsought, unexpected, and, ever since Kate
Erlton's appeal, Jim Douglas had felt a strange attraction toward
pure chance. So he took out a note from his pocket-book and laid it
in the Baharupa's hand.
"You asked fifty," he said, "I give a hundred; but with the branch
of the neem-tree between us two."
Tiddu gave him an admiring look. "With the sacred 'Lim ke dagla'
between us, and Mighty Murri-am herself to see it grow," he echoed.
"Is the Huzoor satisfied?"
"Khutm."
"Khutm." The echo came from Tara's voice, but it had a ring in it
which made him turn, anticipating some surprise. She was standing
not far off, below the plinth, as he was, having stepped out from the
shadow of the trees at his approach, and she was swathed from
head to foot in the white veil of orthodox widowhood, which
encircled her face like a cere-cloth. Even in the moonlight he could
see the excitement in her face, the glitter in the large, wild eyes.
"That the end has come; the end at last!" she cried theatrically;
every fold of her drapery, though she stood stiff as a corpse,
seeming to be instinct with fierce vitality.
"I want nothing," she replied sullenly. "A suttee wants nothing in
this world, and I am suttee. I have been the master's servant for
gratitude's sake--now I am the servant of God for righteousness'
sake." So far she had, spoken as if the dignified words had been
pre-arranged; now she paused in a sort of wistful anger at the
indifference on his face. The words meant so much to her, and, as
she ceased from them, their controlling power seemed to pass also,
and she flung out her arms wildly, then brought them down in
stinging blows upon her breasts.
The cry was full of exalted resolve and despair. It made Jim
Douglas step up to her, and seizing both hands, hold them fast.
"Don't be a fool, Tara!" he said sternly. "Tell me, sensibly, what all
this means. Tell me what you are going to do."
His touch seemed to scorch her, for she tore herself away from it
vehemently; yet it seemed also to quiet her, and she watched him
with somber eyes for a minute ere replying: "I am going to Holy
Gunga. Where else should a suttee go? The Water will not reject me
as the Fire did, since, before God! I am suttee. As the master
knows,"--her voice held a passionate appeal,--"I have been suttee all
these long years. Yet now I have given up all--all!"
"What a pity!" he said, after a moment's pause had told him that
it would be well to try and take the starch out of her resolution by
fair means or foul, leaving its cause for future inquiry. "You had such
nice hair. I used to admire it very much."
Her hands fell slowly, a vague terror and remorse came to her
eyes; and he pursued the advantage remorselessly. "Why did you
cut it off?" He knew, of course, but his affected ignorance took the
color, the intensity from the situation, by making her feel her coup
de theatre had failed.
"That settles it, Tara. You can go to Gunga now if you like, and
bathe and be as holy as you like. But there will be no Fire or Water.
Do you understand?"
She looked at the hand holding the hair with the oddest
expression, though she said obstinately, "I shall drown if I choose."
"What is the Huzoor going to do with it?" she asked, and the
oddness had invaded her voice.
"Keep it," he retorted. "And by all, these thirty thousand and odd
gods of yours, I'll say it was a love-token if I choose. And I will if you
are a fool." He drew out a small gold locket attached to the
Brahminical thread he always wore, and began methodically to fit
the curl into it, wondering if this cantrip of his--for it was nothing
more--would impress Tara. Possibly. He had found such suggestions
of ritual had an immense effect, especially with the womenkind who
were for ever inventing new shackles for themselves; but her next
remark startled him considerably.
"Is the bibi's hair in there too?" she asked. There was a real
anxiety in her tone, and he looked at her sharply, wondering what
she would be at.
"There was no need to thrust this slave away," she said proudly.
"Tara, the Rajputni, will go without that. She will go to Holy Gunga
and be purged of inmost sin. Then she will return and claim her right
of suttee at the master's hand. Till then he may keep what he stole."
"He means to keep it," retorted the master savagely, for he had
come to the end of his patience. "Though what this fuss about
suttee means I don't know. You used to be sensible enough. What
has come to you?"
Then the shadow left him and disappeared with her among the
trees. He did not try to call her back. That answer left him helpless.
But as, after climbing the stairs, he passed slowly from one to
another of the old familiar places in the pleasant pavilions, the
mystery of such womanhood as Tara Devi's and little Zora's
oppressed him. Their eternal cult of purely physical passion, their
eternal struggle for perfect purity and constancy, not of the soul, but
the body; their worship alike of sex and He who made it seemed
incomprehensible. And as he turned the key in the lock for the last
time, he felt glad to think that it was not likely the problem would
come into his life again; even though he carried a long lock of black
hair with him. It was an odd keepsake, but if he was any judge of
faces his cantrip had served his purpose; Tara would not commit
suicide while he held that hostage.
ebookbell.com