0% found this document useful (0 votes)
380 views

Download Complete Clean Code in Python Develop maintainable and efficient code 2nd Edition Anaya PDF for All Chapters

The document provides information on various eBooks available for download, including titles focused on Python programming and clean code practices. It highlights the second edition of 'Clean Code in Python' by Mariano Anaya, which emphasizes developing maintainable and efficient code. Additionally, it mentions other related resources and the benefits of subscribing to the Packt digital library for access to a wide range of technical content.

Uploaded by

powalculey6a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
380 views

Download Complete Clean Code in Python Develop maintainable and efficient code 2nd Edition Anaya PDF for All Chapters

The document provides information on various eBooks available for download, including titles focused on Python programming and clean code practices. It highlights the second edition of 'Clean Code in Python' by Mariano Anaya, which emphasizes developing maintainable and efficient code. Additionally, it mentions other related resources and the benefits of subscribing to the Packt digital library for access to a wide range of technical content.

Uploaded by

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

Download the Full Version of the Ebook with Added Features ebookname.

com

Clean Code in Python Develop maintainable and


efficient code 2nd Edition Anaya

https://ebookname.com/product/clean-code-in-python-develop-
maintainable-and-efficient-code-2nd-edition-anaya/

OR CLICK HERE

DOWLOAD NOW

Download more ebook instantly today at https://ebookname.com


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

Python phrasebook essential code and commands 5. print


Edition Dayley

https://ebookname.com/product/python-phrasebook-essential-code-and-
commands-5-print-edition-dayley/

ebookname.com

Python Mastery A Code Like a Pro Guide for Python


Beginners 1st Edition Jonathan Bates

https://ebookname.com/product/python-mastery-a-code-like-a-pro-guide-
for-python-beginners-1st-edition-jonathan-bates/

ebookname.com

2006 International Plumbing Code 1st Edition International


Code Council (Icc)) International Code Council

https://ebookname.com/product/2006-international-plumbing-code-1st-
edition-international-code-council-icc-international-code-council/

ebookname.com

Caliban s Voice The Transformation of English in Post


Colonial Literatures 1st Edition Bill Ashcroft

https://ebookname.com/product/caliban-s-voice-the-transformation-of-
english-in-post-colonial-literatures-1st-edition-bill-ashcroft/

ebookname.com
The Democratic Promise The Individual Within the Community
First Printing Edition Constance Goh

https://ebookname.com/product/the-democratic-promise-the-individual-
within-the-community-first-printing-edition-constance-goh/

ebookname.com

Handbook of Infrared Spectroscopy of Ultrathin Films 1st


Edition Valeri P. Tolstoy

https://ebookname.com/product/handbook-of-infrared-spectroscopy-of-
ultrathin-films-1st-edition-valeri-p-tolstoy/

ebookname.com

ADR in Employment Law Chris Chapman

https://ebookname.com/product/adr-in-employment-law-chris-chapman/

ebookname.com

Mechanisms of Morphogenesis 1st Edition Jamie Davies

https://ebookname.com/product/mechanisms-of-morphogenesis-1st-edition-
jamie-davies/

ebookname.com

The Handbook of Advanced Materials Enabling New Designs


1st Edition James K. Wessel

https://ebookname.com/product/the-handbook-of-advanced-materials-
enabling-new-designs-1st-edition-james-k-wessel/

ebookname.com
Buying In The Secret Dialogue Between What We Buy and Who
We Are First Edition Rob Walker

https://ebookname.com/product/buying-in-the-secret-dialogue-between-
what-we-buy-and-who-we-are-first-edition-rob-walker/

ebookname.com
Clean Code in Python
Second Edition

Develop maintainable and efficient code

Mariano Anaya

BIRMINGHAM - MUMBAI
Clean Code in Python
Second Edition
Copyright © 2020 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing or its dealers and distributors, will be held liable for any damages caused
or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

Producers: Tushar Gupta


Acquisition Editor – Peer Reviews: Divya Mudaliar
Content Development Editor: Bhavesh Amin
Technical Editor: Karan Sonawane
Project Editor: Mrunal Dave
Copy Editor: Safis Editing
Proofreader: Safis Editing
Indexer: Tejal Soni
Presentation Designer: Ganesh Bhadwalkar

First published: August 2018


Second Edition: December 2020

Production reference: 2281220

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-80056-021-5

www.packt.com
packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos,
as well as industry leading tools to help you plan your personal development and
advance your career. For more information, please visit our website.

Why subscribe?
• Spend less time learning and more time coding with practical eBooks and
Videos from over 4,000 industry professionals
• Learn better with Skill Plans built especially for you
• Get a free eBook or video every month
• Fully searchable for easy access to vital information
• Copy and paste, print, and bookmark content

Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.Packt.com
and as a print book customer, you are entitled to a discount on the eBook copy. Get
in touch with us at [email protected] for more details.

At www.Packt.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters, and receive exclusive discounts and offers on Packt
books and eBooks.
Contributors

About the author


Mariano Anaya is a software engineer who spends most of his time creating
software and mentoring fellow programmers. Mariano's primary areas of interest are
software architecture, functional programming, and distributed systems. He was a
speaker at Euro Python in 2016 and 2017, and FOSDEM 2019. To find out more about
him, you can refer to his GitHub account with the username rmariano.

Dedicated to my family and friends, for their unconditional support.


About the reviewer
Tarek Ziadé has been a Python developer for a long time. Back in the old days, he
founded the French Python User group (AFPY) and was involved in the language
development around packaging. He has written books about Python in both French
(his native language) and English.

Tarek worked at Mozilla for over a decade, building tools and services, leveraging
Python's awesomeness in projects at scale. He now works as a principal engineer
at Elastic.
Table of Contents
Prefaceix
Chapter 1: Introduction, Code Formatting, and Tools 1
Introduction2
The meaning of clean code 2
The importance of having clean code 3
Some exceptions 5
Code formatting 6
Adhering to a coding style guide on your project 6
Documentation9
Code comments 9
Docstrings 10
Annotations 13
Do annotations replace docstrings? 17
Tooling19
Checking type consistency 20
Generic validations in code 22
Automatic formatting 23
Setup for automatic checks 26
Summary28
References28
Chapter 2: Pythonic Code 29
Indexes and slices 30
Creating your own sequences 32
Context managers 34
Implementing context managers 37
Comprehensions and assignment expressions 40
[i]
Table of Contents

Properties, attributes, and different types of methods for objects 43


Underscores in Python 44
Properties 46
Creating classes with a more compact syntax 49
Iterable objects 52
Creating iterable objects 53
Creating sequences 56
Container objects 57
Dynamic attributes for objects 59
Callable objects 61
Summary of magic methods 63
Caveats in Python 64
Mutable default arguments 64
Extending built-in types 66
A brief introduction to asynchronous code 68
Summary70
References71
Chapter 3: General Traits of Good Code 73
Design by contract 74
Preconditions 76
Postconditions 76
Pythonic contracts 77
Design by contract – conclusions 77
Defensive programming 78
Error handling 78
Value substitution 79
Exception handling 80
Using assertions in Python 88
Separation of concerns 90
Cohesion and coupling 91
Acronyms to live by 92
DRY/OAOO 92
YAGNI 94
KIS 95
EAFP/LBYL 97
Inheritance in Python 99
When inheritance is a good decision 99
Anti-patterns for inheritance 100
Multiple inheritance in Python 103
Method Resolution Order (MRO) 104
Mixins 106
Arguments in functions and methods 107
[ ii ]
Table of Contents

How function arguments work in Python 107


How arguments are copied to functions 107
Variable number of arguments 109
Positional-only parameters 114
Keyword-only arguments 115
The number of arguments in functions 117
Function arguments and coupling 117
Compact function signatures that take too many arguments 118
Final remarks on good practices for software design 120
Orthogonality in software 120
Structuring the code 122
Summary123
References124
Chapter 4: The SOLID Principles 125
The single responsibility principle 126
A class with too many responsibilities 126
Distributing responsibilities 128
The open/closed principle 129
Example of maintainability perils for not following the OCP 130
Refactoring the events system for extensibility 133
Extending the events system 135
Final thoughts about the OCP 137
Liskov's substitution principle 137
Detecting LSP issues with tools 138
Using mypy to detect incorrect method signatures 138
Detecting incompatible signatures with pylint 140
More subtle cases of LSP violations 141
Remarks on the LSP 144
Interface segregation 144
An interface that provides too much 146
The smaller the interface, the better 146
How small should an interface be? 148
Dependency inversion 149
A case of rigid dependencies 150
Inverting the dependencies 150
Dependency injection 152
Summary154
References155
Chapter 5: Using Decorators to Improve Our Code 157
What are decorators in Python? 158
Function decorators 159
Decorators for classes 160
[ iii ]
Table of Contents

Other types of decorator 165


More advanced decorators 165
Passing arguments to decorators 165
Decorators with nested functions 166
Decorator objects 168
Decorators with default values 169
Decorators for coroutines 172
Extended syntax for decorators 175
Good uses for decorators 176
Adapting function signatures 176
Validating parameters 178
Tracing code 178
Effective decorators – avoiding common mistakes 178
Preserving data about the original wrapped object 179
Dealing with side effects in decorators 181
Incorrect handling of side effects in a decorator 182
Requiring decorators with side effects 184
Creating decorators that will always work 186
Decorators and clean code 189
Composition over inheritance 189
The DRY principle with decorators 192
Decorators and separation of concerns 193
Analysis of good decorators 195
Summary197
References197
Chapter 6: Getting More Out of Our Objects with Descriptors 199
A first look at descriptors 200
The machinery behind descriptors 200
Exploring each method of the descriptor protocol 203
The get method 203
The set method 205
The delete method 207
The set name method 210
Types of descriptors 211
Non-data descriptors 212
Data descriptors 214
Descriptors in action 217
An application of descriptors 217
A first attempt without using descriptors 217
The idiomatic implementation 219
Different forms of implementing descriptors 222
The issue of shared state 222
Accessing the dictionary of the object 223

[ iv ]
Table of Contents

Using weak references 224


More considerations about descriptors 225
Reusing code 225
An alternative to class decorators 226
Analysis of descriptors 230
How Python uses descriptors internally 230
Functions and methods 230
Built-in decorators for methods 234
Slots 235
Implementing descriptors in decorators 237
Final remarks about descriptors 237
Interface of descriptors 237
Object-oriented design of the descriptors 238
Type annotations on descriptors 238
Summary239
References240
Chapter 7: Generators, Iterators, and Asynchronous
Programming241
Technical requirements 242
Creating generators 242
A first look at generators 242
Generator expressions 246
Iterating idiomatically 247
Idioms for iteration 247
The next() function 249
Using a generator 250
Itertools 251
Simplifying code through iterators 252
The iterator pattern in Python 255
Coroutines259
The methods of the generator interface 260
close() 260
throw(ex_type[, ex_value[, ex_traceback]]) 261
send(value) 263
More advanced coroutines 266
Returning values in coroutines 266
Delegating into smaller coroutines – the 'yield from' syntax 268
Asynchronous programming 273
Magic asynchronous methods 275
Asynchronous context managers 276
Other magic methods 277
Asynchronous iteration 278
Asynchronous generators 280
Summary281
[v]
Table of Contents

References282
Chapter 8: Unit Testing and Refactoring 285
Design principles and unit testing 286
A note about other forms of automated testing 287
Unit testing and agile software development 288
Unit testing and software design 289
Defining the boundaries of what to test 293
Tools for testing 293
Frameworks and libraries for unit testing 294
unittest 295
pytest 301
Code coverage 306
Mock objects 309
Refactoring315
Evolving our code 316
Production code isn't the only one that evolves 318
More about testing 319
Property-based testing 320
Mutation testing 320
Common themes in testing 323
Boundaries or limit values 323
Classes of equivalence 323
Edge cases 324
A brief introduction to test-driven development 325
Summary325
References326
Chapter 9: Common Design Patterns 327
Design pattern considerations in Python 328
Design patterns in action 329
Creational patterns 330
Factories 330
Singleton and shared state (monostate) 331
Builder 336
Structural patterns 337
Adapter 337
Composite 339
Decorator 340
Facade 343
Behavioral patterns 344
Chain of responsibility 345
The template method 348
Command 349
State 350

[ vi ]
Table of Contents

The null object pattern 355


Final thoughts about design patterns 358
The influence of patterns over the design 358
Design patterns as theory 359
Names in our models 360
Summary360
References361
Chapter 10: Clean Architecture 363
From clean code to clean architecture 364
Separation of concerns 364
Monolithic applications and microservices 366
Abstractions 367
Software components 368
Packages 369
Managing dependencies 372
Other considerations when managing dependencies 374
Artifact versions 376
Docker containers 376
Use case 378
The code 379
Domain models 380
Calling from the application 382
Adapters 383
The services 384
Analysis 388
The dependency flow 388
Limitations 389
Testability 389
Intention revealing 390
Summary390
References391
Summing it all up 391
Share your experience 392
Other Books You May Enjoy 393
Index395

[ vii ]
Other documents randomly have
different content
Having beheld these professional curiosities, he left the Mogul
court, and proceeded by the ordinary route towards Bengal. The
Ganges, where he crossed it, in company with Bernier, he found no
larger than the Seine opposite the Louvre, an insignificant stream
which scarcely deserves the name of a river. At Benares he
observed the narrowest streets and the loftiest houses which he had
seen in Hindostan, a circumstance remarked by all travellers, and
among the rest by Heber, who says, “The houses are mostly lofty;
none, I think, less than two stories, most of three, and several of five
or six, a sight which I now for the first time saw in India. The streets,
like those of Chester, are considerably lower than the ground floors
of the houses, which have mostly arched rows in front, with little
shops behind them. Above these the houses are richly embellished
with verandahs, galleries, projecting oriel windows, and very broad
and overhanging coves, supported by carved brackets.” The
opposite sides of the streets stand so near to each other in many
places that they are united by galleries. The number of stone and
brick houses in the city are upwards of twelve thousand, of clay
houses sixteen thousand; and the population in 1803 considerably
exceeded half a million. Benares, according to the Brahmins, forms
no part of the terrestrial globe, but rests upon the thousand-headed
serpent Anarta, or Eternity: or, according to others, on the point of
Siva’s trident, and hence no earthquakes are ever felt there. The
Great Lingam, or Phallies, of Benares, is said to be a petrifaction of
Siva himself; and the worship of this emblem of the godhead so
generally prevails here, that the city contains at least a million
images of the Lingam. This holy city, the Brahmins assure us, was
originally built of gold, but for the sins of mankind it was successively
degraded to stone, and brick, and clay.
From Benares he proceeded through Patna and Rajmahel to
Daca, then a flourishing city; whence, having disposed of numerous
jewels to the nawâb, he returned to Delhi.
To avoid repetitions and perplexing breaks in the narrative, I have
paid no attention to the date of his visits to this or that city; and,
indeed, so confused were his notes and his memory, that he does
not seem to have known very well himself during which of his
journeys many events which he relates took place. Into the
particulars of his voyage to Ceylon, Sumatra, and Java it is
unnecessary to enter, more full and curious accounts of those
islands occurring in other travellers.
On his return to France from his fifth visit to the East, he married
an ancient damsel, to borrow an epithet from Burke, merely from
gratitude to her father, who was a jeweller, and had rendered him
several essential services. After this he undertook one more journey
into Asia, with merchandise to the value of four hundred thousand
livres, consisting of curious clocks, crystal and agate vases, pearls,
and other jewelry. This expedition occupied him six years, during
which he advanced farther towards the east than he had hitherto
done; and having in this and his other journeys amassed
considerable wealth, he returned with a splendid assortment of
diamonds to France, having been engaged upwards of forty years in
travelling. Disposing of these jewels advantageously to the French
king, who granted him a patent of nobility, he now conceived that all
his wanderings were at an end, and began to think of enjoying the
wealth he had purchased with so much time and toil and difficulty.
Experience, however, had not rendered him wise. Puffed up with the
vanity inspired by his patent of nobility, his whole soul was now
wrapped up in visions of luxury and magnificence. He rented a
splendid house, set up a carriage, and hired a number of valets. The
nobility, who no doubt devoured his adventures and his dinners with
equal greediness, flocked about him, invited, caressed, flattered, and
ruined him.

Live like yourself was now my lady’s word!

He was prevailed upon by some of his noble friends, who


supposed him to be possessed of the wealth of Crœsus, to purchase
a baronial castle and estate near Lyons, the repairs of which, united
with the absurd expenses of his household, quickly threatened to
plunge him into the poverty and obscurity from which he originally
rose. To accelerate this unhappy catastrophe, undoubtedly owing
principally to his own folly, his nephew, to whose management he
had intrusted a valuable venture in the hope of retrieving his
shattered fortune, proved dishonest, married, and remained in the
East, appropriating to his own use the property of his uncle. To
increase the consternation caused in his family by these private
calamities, it was rumoured that the edict of Nantes was about to be
revoked, which induced him immediately to dispose of his estate,
and prepare to emigrate with the great body of the Protestants out of
France. Time for proper negotiations not being allowed, the barony
was sold for considerably less than it had cost him; and every thing
now going unprosperously with our noble jeweller, his family retired
to Berlin, while he repaired, in an obscure manner, to Paris, in quest
of funds for another journey into the East.
Tavernier was now in his eighty-third year, broken in spirits, ruined
in fortune, and bending beneath the effects of age; but his courage
had not forsaken him. He succeeded by dint of great exertions in
getting together a considerable venture, and departed for Hindostan
by way of Russia and Tartary. That he arrived safely at Moscow is
tolerably certain; but in this city we lose sight of him; some writers
affirming that he died there, while others more confidently assert,
that having spent some time at this ancient capital of Russia, he
continued his journey, and embarked with his merchandise in a bark
upon the Volga, with the design of descending that river to the
Caspian Sea. Whether this wretched bark foundered in the stream,
or, which is more probable, was plundered, and its crew and
passengers massacred by the Tartars, is what has never been
ascertained. At all events, Tavernier here disappears, for no tidings
of him ever reached France from that time. He is supposed to have
died in 1685, or 1686.
His works have gone through several editions, and may be
consulted with advantage by the students of Asiatic manners, though
the style, which is that of some miserable compiler whom he
employed to digest his rough memoirs, be intolerably bald and
enervate; while the method and arrangement are, perhaps, the worst
that could have been adopted. Had he contented himself with the
simple form of a journal, narrating events as they occurred, and
describing things as they presented themselves to his notice, he
could not have been more prolix, and would undoubtedly have
rendered his work more agreeable and useful. As a traveller, he is
undoubtedly entitled to the praise of enterprise and perseverance; no
dangers appalled, no misfortunes depressed him; but his remarks
are always rather the remarks of a trader than of a traveller. Wealth
was his grand object; knowledge and fame things of secondary
consideration. The former, however, he gained and lost; his
reputation, though far less brilliant than that of many other travellers,
remains to him, and will long remain a monument of what can be
effected by persevering mediocrity.
FRANÇOIS BERNIER.
Born about 1624.—Died 1688.

This distinguished traveller was born at Angers about the year


1624. Though educated for the medical profession, and actuated in
an extraordinary manner by that ardour for philosophical speculation
which pervaded his literary contemporaries, the passion for travelling
prevailed over every other; so that, having prepared himself by
severe study for visiting distant countries with advantage, and taken
his doctor’s degree at Montpellier, he departed from France in the
year 1654, and passed over into Syria. From thence he proceeded to
Egypt, where he remained upwards of a year. In this country he
assiduously occupied himself in inquiries respecting the sources of
the Nile, the time and manner of its rise, the causes and nature of
the plague, and the fall of that dew which is said to deprive its virus
of all activity. Being at Rosetta eight or ten days after this dew had
shed its mysterious moisture over the earth, he had an opportunity,
which had like to have cost him dear, of discovering the absurdity of
the popular belief upon this subject. He was at supper with a party of
friends at the house of M. Bermon, vice-consul of France, when
three persons were suddenly stricken with the plague. Of these, two
died in the course of eight days; and the third, who was M. Bermon
himself, seemed likely to follow their example, when our medical
traveller undertook the treatment of his disease. What medicines he
administered to his patient he has not stated, but he lanced the
pestiferous pustules which rose upon the skin; and either by
performing this operation, or by inhaling the infected atmosphere of
the sick chamber, himself caught the infection. The patient now
recovered, while the physician in turn became the prey of disease.
When Bernier perceived himself to be in the plague, the first step he
took was to swallow an emetic of butter of antimony, which, together
with the natural force of his constitution, subdued the disorder, and
enabled him in the course of three or four days to resume his
ordinary pursuits. He was, perhaps, somewhat indebted to his
Bedouin attendant for the preservation of his cheerfulness and
tranquillity during his illness. This man, relying, or appearing to rely,
upon the doctrine of predestination, in order to cheer and encourage
him, by showing him how lightly he thought of the matter, used daily
to eat the remainder of the food which his sick master had touched.
Having satisfied his curiosity respecting Egypt, and visited Mount
Sinai and the neighbouring deserts, he proceeded to Suez, and
embarked in an Arab vessel for Jidda. The Turkish bey, then
governor of this post, had deluded him with the hope of being able to
visit Mecca and the Kaaba, places interdicted to all Christians; but
having waited for this permission thirty-four days, and perceiving no
likelihood of obtaining it, he again embarked; and sailing for fifteen
days along the coast of Arabia Felix, or Yeman, arrived at Mokha,
near the straits of Babelmandel. During his stay in this city, he
partook of the hospitality of Murad, an Armenian Christian, and a
native of Aleppo, but who had settled in Abyssinia, whence he was
now come into Arabia with a number of black slaves to be disposed
of for the benefit of the Abyssinian king, from whom he likewise bore
the customary annual present which that august monarch made to
the English and Dutch East India companies, in the hope of receiving
one of greater value in return. With the proceeds of the slaves Indian
merchandise was purchased; so that in exchange for a few useless
subjects, his Abyssinian majesty annually received a large quantity
of fine muslins, spices, and diamonds. With this honest Armenian
merchant our traveller had a very characteristic transaction, which,
although it happened some time after the visit to Mokha, may very
well come in here. Murad, it seems, in addition to his Aleppine wife,
maintained a harem of Nubian or Abyssinian girls, by one of whom
he had a son, who to the pure black complexion of his mother united
the fine handsome features peculiar to the Caucasian race. This
noble little fellow Murad, who was desirous of turning the produce of
his harem to account, offered to sell M. Bernier for fifty rupees; but
observing that his guest was extremely anxious to possess the prize,
he suddenly changed his mind, and refused to part with his darling
son for less than three hundred rupees. At this strange instance of
rapacity our traveller became offended, and broke off the
negotiation; though, as he tells us, he was peculiarly desirous of
concluding the bargain, as much for the sake of the boy as for the
purpose of seeing a father sell his own child. There seems, however,
to be some reason for suspecting that the Armenian was not quite so
nearly related to the boy as he pretended, his paternity being in all
probability feigned, for the purpose of enhancing the price of his little
slave.
From Mokha it was Bernier’s intention to have crossed the Red
Sea to the island of Mesowa and Arkiko, from whence he expected
an easy passage might be obtained into the country of Habesh or
Abyssinia. To dissuade him from his purpose, however, Murad and
others, who might, perhaps, have had some sinister motives for their
conduct, assured him, that since the expulsion of the Jesuits,
effected by the intrigues of the queen-mother, no Roman Catholic
was secure in the country, where a poor Capuchin friar, who
attempted to enter it by way of Snakin, had recently lost his head.
These and other considerations turned the current of his ideas. He
abandoned Africa, and, embarking on board of an Indian ship bound
for Surat, sought the shores of Hindostan.
On the arrival of our traveller in India, those fratricidal wars
between the sons of Shah Johan, which terminated with the
dethronement of the aged emperor and the accession of
Aurungzebe to the throne of Delhi, had already commenced, and
confusion, terror, and anarchy prevailed throughout the empire.
Nevertheless Bernier hastened to the capital, where, finding that
partly by robbery, partly by the ordinary expenses of travelling, his
finances had been reduced to a very low ebb, he contrived to be
appointed one of the physicians to the Great Mogul.
About twelve months before Bernier’s appointment to this office,
the emperor, who, though upwards of seventy, was immoderately
addicted to the excesses of the harem, had become grievously ill
from that disorder, it is supposed, which cut off untimely the
chivalrous rival of the Emperor Charles V. His four sons imagining,
and all, indeed, excepting the eldest, ardently desiring, that he might
be drawing near his end, had at once rushed to arms, and with
powerful armaments collected in their various subahs, or
governments, had advanced towards the capital, each animated by
the hope of opening himself a way to musnud through the hearts of
his brethren. Their battles, negotiations, intrigues, and mutual
treachery, though related in a vivid and energetic manner by Bernier,
can find no place in this narrative. Aurungzebe, having defeated and
put to flight the Rajah Jesswunt Singh, was now advancing towards
the capital, when his eldest brother, Dara, incensed at his audacity,
and naturally impatient of delay, advanced with the imperial army
towards the Chumbul and that range of mountain passes which
extends between the Jumna and Guzerat. Here a battle was fought,
in which Aurungzebe was victor. Dara, with the wretched remnant of
his forces, fled towards Ahmedabad, the ancient Mohammedan
capital of Guzerat. In this miserable plight he was met by Bernier,
whom the prince, who had known him at Delhi, and had now no
medical attendant, compelled to follow in his train. In the East
misfortune is singularly efficacious in thinning the ranks of a prince’s
retinue. Dara was now accompanied by little more than two
thousand men, and this number, moreover, was daily diminished by
the peasantry of the country, a wild and savage race, who hung upon
his rear, pillaging and murdering all those who lagged for a moment
behind the body of the army. It was now the midst of summer; the
heat was tremendous; and the fugitives, without baggage or tents,
had to make their way over the naked sandy plains of Ajmere, by
day exposed to the intolerable rays of the sun, and by night to the
dews and chilling blasts which sometimes issue from the northern
mountains. However, the prince and his followers pushed on rapidly,
and now began to entertain some hopes of safety, having
approached to within one day’s journey of Ahmedabad, the governor
of which had been promoted to the post by Dara himself. But the
emissaries and the gold of Aurungzebe had already done their work
at Ahmedabad. The treacherous governor, on hearing of the near
approach of the prince, wrote to prohibit his drawing nearer the city,
informing him that if he persisted he would find the gates shut, and
the people in arms against him. On the evening before this news
was brought to him, Dara had taken refuge with his harem in a
caravansary, into which, in spite of the natural aversion of all
orientals to introduce strangers among the women of their anderûn,
he kindly invited Bernier, apprehending lest the sanguinary
peasantry should beat out his brains in the darkness. Here it was
melancholy to see the shifts to which this unfortunate prince was
driven to have recourse for the preserving, even in this last extremity,
of the dignity of his harem; for, possessing neither tent nor any other
effectual covering, he caused a few slight screens to be fixed up, in
order to maintain some semblance of seclusion, and these were kept
steady by being tied to the wheels of Bernier’s wagon.
Meanwhile, as the determination of the governor of Ahmedabad
was not yet known, the most intense anxiety prevailed among the
fugitives. Every gust which moaned along the surrounding waste
appeared to their half-slumbering senses to announce the approach
of some messenger. The hours, which seem to flit away so rapidly
when men are happy, now appeared so many ages. Time and the
wheeling stars above their heads seemed to stand still; and their
very souls were sick with expectation. At length, as the red dawn
began to appear in the east, a single horseman was discovered
scouring across the plain. His tidings from Ahmedabad were such as
have been related above. Upon hearing this dreadful intelligence, the
ladies of the harem, who had hitherto consoled themselves with the
hope of tasting a little repose in that city, which had become a kind of
land of promise in their eyes, gave themselves up wholly to despair,
and tears, sobs, and the most passionate lamentations burst
unrestrainedly forth, and brought tears into the eyes of many not
much used to weeping. Every thing was now thrown into the utmost
trouble and confusion. Each person looked at the face of his
neighbour, in the hope of discovering some ray of consolation, some
sign of counsel, fore-thought, or magnanimity. But all was blank. Not
a soul could advise any thing for the general safety, or knew how to
avert the doom which impended over himself. Presently, however,
Dara, half-dead with grief, came out to his people, and addressed
himself now to one person, now to another, even to the meanest
soldier. He perceived that terror had seized upon every soul, and
that they were all about to abandon him. What was to be his fate?
Whither could he fly? It was necessary to depart instantly. The
condition of the army may be conjectured from that of our traveller.
The wagon in which he travelled had been drawn by three large
Guzerat oxen, one of which had died on the previous day from
fatigue, another was now dying, and the third was wholly unable to
move. Nevertheless, the prince, who stood in need of his aid both for
himself and for one of his wives, who had been wounded in the leg,
found it absolutely impossible to procure either horse, ox, or camel
for his use, and was therefore compelled to leave him behind.
Bernier saw him depart with tears in his eyes, accompanied at most
by four or five horsemen, and two elephants said to be loaded with
silver and gold. He struck off towards Tettabakar, through pathless
deserts of sand, where, for the most part, not a drop of water was to
be found; and though, as afterward appeared, he actually succeeded
in reaching the point of destination, several of his followers, and,
indeed, many of his harem, died by the way of thirst or fatigue, or
were murdered by the banditti.
Bernier, being thus abandoned by the ill-fated prince, in a country
overrun with robbers, was at a loss what course to pursue. The
circumstances of the moment, however, left him no time for
deliberation; for no sooner had Dara and his train disappeared than
our traveller’s wagon was surrounded by the banditti, who forthwith
commenced the work of plunder. Fortunately, his servant and driver
preserved their presence of mind, and, addressing themselves to the
marauders, began to inquire whether they would thus pillage the
effects of a man who was the first physician in the world, and had
already been deprived of the most valuable part of his property by
the satellites of Dara. At the mention of the word physician these
fierce banditti, who, like all barbarians, entertained a kind of innate
reverence for the children of Esculapius, were rendered as mild as
gazelles, and their hostile intentions were changed into friendship.
They now regarded this second Pæon as their guest, and, having
detained him seven or eight days, kindly furnished him with an ox to
draw his wagon, and served him as guides and guards until the
towers of Ahmedabad appeared in sight. At this city he remained
several days, when an emir, returning thence to Delhi, afforded him
the protection of his authority, and enabled him to perform the
journey with safety. The road over which they travelled exhibited
numerous traces of the calamities of the times, being strewed at
intervals with the dead bodies of men, elephants, camels, horses,
and oxen, the wrecks of the wretched army of Dara.
Aurungzebe, having outwitted and imprisoned his father, was now
in possession of Delhi and the imperial throne, and exerted all the
force of his versatile and subtle genius to gain possession of the
persons of his enemies. Dara, the principal of these, was soon
afterward betrayed into his hands, and brought to Delhi upon an
elephant, bound hand and foot, with an executioner behind him, who
upon the least movement was to cut off his head. When he arrived at
the gate of the city, Aurungzebe began to deliberate whether it would
be altogether safe, under present circumstances, to parade him in
this style through the streets, considering the affection which the
people had always borne him; but it was at length determined to
hazard the step, for the purpose of convincing those who admired
him of his utter fall, and of the consequent extinction of their hopes.
His rich garments, his jewelled turban, his magnificent necklace of
pearls, had been taken from him, and a dirty and miserable dress,
such as would have suited some poor groom, bestowed in their
stead; and thus habited, and mounted with his little son upon a poor
half-starved elephant, he was led through the streets, lanes, and
bazaars of the capital, that the people might behold the fortune of
their favourite, and despair of his ever rising again. Expecting that
some strange revolution or horrible slaughter would inevitably ensue,
Bernier had repaired on horseback, with a small party of friends and
two stout servants, to the grand bazaar, where the most prodigious
crowds were assembled, in order to witness whatever might take
place; but although the multitude burst into tears at the sight, and
overwhelmed the wretch who had betrayed him, and was then on
horseback by his side, with the most dire imprecations, not a sword
was drawn, or a drop of blood spilt.
During the course of these public events Bernier became
physician to Danekmand Khan, the favourite of Aurungzebe. Upon
this appointment, he seems to have been introduced at court, and
presented to the emperor; upon which occasion he kissed the hem
of the imperial garment, and offered, for so custom ordered, eight
rupees as a gift to the richest sovereign upon earth. He was now
perfectly at his ease, enjoying, besides a liberal salary, which seems
to have answered all his wishes, the friendship of the khan, a
learned, inquisitive, and generous-minded man, who devoted those
hours which others spent in debauchery to the discussion of
philosophical questions, and conversations on the merits of
Descartes and Gassendi. By the favour of this nobleman the entry to
the palace was open to him on all public occasions. He witnessed
the audience of foreign ambassadors, the pomp of the imperial
banquets, and was admitted, under certain circumstances, into the
recesses of the harem.
Upon the termination of the civil wars, the Usbecks of Balkh and
Samarcand, who, having formerly offered a grievous insult to
Aurungzebe when he seemed little likely to ascend the imperial
musnud, had now some reason to apprehend the effects of his
resentment, despatched ambassadors to congratulate him upon his
accession to the throne, and to make him a tender of their services.
When these barbarians were admitted to an audience, Bernier,
according to custom, was present. Being admitted into the imperial
chamber, they made, while yet at a considerable distance from the
throne, their salām to the emperor, after the Indian manner. This
ceremony consisted in thrice placing the hand upon the head, and as
frequently lowering it to the earth; after which they advanced so near
the throne that, had he chosen to do so, the emperor might have
taken their letters from their own hands; but this compliment he did
not condescend to pay them, ordering one of his emirs to receive
and present them to him. Having perused these letters with a serious
air, he caused each of the ambassadors to be presented with a robe
of brocade, a turban, and a scarf or girdle of embroidered silk. The
presents were then brought forward. They consisted of several
boxes of lapis lazuli, a number of long-haired camels, several
magnificent Tartarian horses, with many camel-loads of fresh fruit,
such as apples, pears, grapes, and melons, articles which their
country usually furnished for the Delhi market, and an equal quantity
of dried fruits, as Bokham prunes, Kishmish apricots or grapes
without stones, and two other species of fine large grapes.
Aurungzebe bestowed high commendations upon each article as it
was presented, praised the generosity of the khans, and having
made some few inquiries respecting the academy of Samarcand,
dismissed the ambassadors with the complimentary wish that he
might see them frequently.
These honest men, who were exceedingly pleased at their
reception, were nevertheless constrained to wait four months at
Delhi before they could obtain their dismissal; during which time they
all fell sick, and many of them died, rather, according to Bernier, from
the bad quality of their food, and their contempt of cleanliness, than
from the effect of the climate. Judging from this specimen, our
traveller pronounced the Usbecks the most avaricious and sordid
people upon earth; for, though furnished by the emperor with the
means of living, they preferred defrauding their stomachs and
hazarding their lives, to the idea of parting with their gold, and
subsisted in a very wretched and mean style. When dismissed,
however, they were treated with great distinction. The emperor and
all his emirs presented them with rich dresses and eight thousand
rupees each; together with splendid robes, a large quantity of
exquisitely flowered brocade, bales of fine muslin, and of silk striped
with gold or silver, and a number of carpets and two jewelled
khaudjars, or poniards, for their masters.
In the hope of learning something respecting their country, Bernier
frequently visited them during their stay, but found them so grossly
ignorant that they were unable to make any important additions to
his knowledge. They invited him to dinner, however, and thus
afforded his curiosity a glance at their domestic manners. Among
them a stranger, as might be expected, was not overwhelmed with
ceremony, and so far they were polite. The viands, which our
traveller considered extraordinary, consisted of excellent horse-flesh,
a very good ragout, and an abundance of pilau, which his robust
hosts found so much to their taste, that during the repast they could
not snatch a single moment to waste on conversation. Their guest,
with infinite good taste, imitated their example, made a hearty dinner;
and then, when the horse-flesh, pilau, and all had been devoured,
they found their tongue, and entertained him with panegyrics upon
their own skill in archery, and the amazonian prowess and ferocity of
their women. In illustration of the latter, they related an anecdote
which, as highly characteristic, may be worth repeating. When
Aurungzebe formerly led an army against the khan of Samarcand, a
party of twenty or thirty Hindoo horsemen attacked a small village,
which they plundered, and were engaged in binding a number of the
inhabitants whom they intended to dispose of as slaves, when an old
woman came up to them and said, “My children, be not so cruel. My
daughter, who is not greatly addicted to mercy, will be here presently.
Retire, if you are wise. Should she meet with you, you are undone.”
The soldiers, however, not only laughed at the old woman and her
counsel, but seized and tied her also. They had not proceeded
above half a league with their booty, when their aged prisoner, who
never ceased turning her eyes towards the village, uttered a scream
of joy, for by the cloud of dust which she beheld rising on the plain
she knew her daughter was advancing to the rescue. On turning
round, the soldiers beheld the amazon mounted on a fiery war-
horse, with her bow and quiver by her side. She now raised her
stentorian voice, and commanded them as they valued their lives to
release their prisoners, and carry back whatever they had taken to
the village, in which case she would spare them. But they regarded
her menaces no more than they had those of her mother. When
three or four of the party, however, had felt the point of her arrows in
their heart, and were stretched upon the earth, they began to be a
little more alarmed, and had recourse to their own bows. But all their
arrows fell short of the mark, while her powerful bow and arm sent
every weapon home, so that she quickly despatched the greater
number of her enemies, and having dispersed and terrified the
remainder, rushed upon them sabre in hand, and hewed them to
pieces.
During the number of years which Bernier spent in Hindostan in a
position peculiarly favourable to observation, he possessed ample
leisure for correcting and maturing his opinions. His views, therefore,
are entitled to the highest respect, the more especially as no trait of
gasconading is visible in his character, and no touch of rhetorical
flourishing in his style. His countrymen, in general, assuming Paris
as the standard of whatever is noble or beautiful in architecture,
describe every thing which differs from their type as inferior; but
Bernier, whom philosophy had delivered from this paltry nationality,
without depreciating the capital of his own country, observes, that
whatever might be its beauties, they would be but so many defects
could the city be transported to the plains of Hindostan, the climate
requiring other modes of building, and different arrangements. Delhi
was, in fact, a magnificent city in his times. Whatever Asia could
furnish of barbaric pomp or gorgeous show was there collected
together, and disposed with as much taste as Mongol or Persian art
could give birth to. Domes of vast circumference and fantastic swell
crowned the summits of the mosques, and towered aloft above the
other structures of the city; palaces, cool, airy, grotesque, with
twisted pillars, balustrades of silver, and roofs of fretted gold;
elephants moving their awkward and cumbrous bulk to and fro,
disguised in glittering housings, and surmounted with golden
houdahs; and gardens, shaded and perfumed by all the most
splendid trees and sweetest flowers of Asia: such were the principal
features of Delhi.
Our traveller did not at first relish the Mussulman music, its loud
ear-piercing tones being too powerful for his tympanum. By degrees,
however, their hautboys of a fathom and a half in length, and their
cymbals of copper or iron not less than a fathom in circumference,
which appeared to make the very earth tremble with their
tremendous clangour, became familiar to his ear, and seemed
delightfully musical, particularly at night, when he lay awake in his
lofty bedchamber, and heard their loud symphonies from a distance.
In a range of turrets within the palace, before which this martial
music was daily heard, was situated the harem, or seraglio, as it was
termed by Europeans in those days. This mysterious part of the
palace Bernier traversed but did not see, having been called in to
prescribe for a great lady of the court, but conducted by a eunuch
blindfold, or with a cashmere shawl thrown over his head and
descending to his feet, through the various chambers and passages.
He learned, however, from the eunuchs, that the harem contained
very noble apartments, each of which was furnished with its reservoir
of running water, and opened upon gardens, with covered walks,
dusky bowers, grottoes, streams, fountains, and immense caves,
into which the ladies retired during the heat of the day. Thus the
inconveniences of the climate were never felt in this secluded
paradise. The most delightful portion of this part of the palace,
according to the eunuchs, was a small tower covered with plates of
gold, and glittering on the inside with azure, gold, mirrors, and the
richest and most exquisite pictures. It overlooked the Jumna, and
thence the ladies could enjoy a fine prospect and the coolest air.
Though by no means liable to be dazzled by pompous exhibitions,
Bernier could not refuse his admiration to the Great Mogul’s hall of
audience, and the splendour of the peacock throne. In fact, the
appearance of this hall upon one of the principal Mohammedan
festivals he considered one of the most remarkable things which he
saw during his travels. Upon entering the spacious and lofty saloon
the first object which met the eye was the emperor himself seated
upon his throne, and attired in the most magnificent and gorgeous
style of the East. His robe was composed of white satin with small
flowers, relieved by a rich border of silk and gold; his turban, of stiff
cloth of gold, was adorned with an aigrette, the stem of which was
crusted with diamonds of prodigious size and value, in the midst of
which a large oriental topaz of unparalleled beauty blazed like a
mimic sun; while a string of large pearls fell from his neck upon his
bosom, like the beads of a devotee. The throne was supported upon
six large feet of massive gold, set with rubies, emeralds, and
diamonds. But its principal ornament were two peacocks, whose
feathers were imitated by a crust of pearls and jewels. The real value
of this throne could not be exactly ascertained, but it was estimated
at four azores, or forty millions of rupees.—At the foot of the throne
stood all the numerous emirs or princes of the court, magnificently
apparelled, with a canopy of brocade with golden fringe overhead,
and all round a balustrade of massive silver, to separate them from
the crowd of ordinary mortals, who took their station without. The
whole riches of the empire seemed collected there in one heap, for
the purpose of dazzling and astonishing the crowd. The pillars of the
saloon were hung round with brocade with a gold ground, and the
whole of the end near the throne was shaded with canopies of
flowered satin, attached with silken cords and nets of gold. Upon the
floor immense silken carpets, of singular fineness and beauty, were
spread for the feet of the courtiers. In short, wherever the eye could
turn, the heart and secret thoughts of the assembly not being visible,
its glances alighted upon a blaze of grandeur, above, around, below,
until the aching sight would gladly have sought repose among the
serener and more soothing beauties of external nature.
In the several visits which Bernier made to Agra, the object which
principally attracted his attention was the celebrated taj, or tomb, of
Nourmahal, the favourite wife of Shah Jehan, which he considered
far more worthy than the pyramids to be enumerated among the
wonders of the world. Leaving the city and proceeding towards the
east, through a long, broad street, running between lofty garden-
walls and fine new houses, he entered the imperial gardens. Here
numerous structures, varying in their forms, yet all possessing their
peculiar beauties, courted observation; but the enormous dome of
the mausoleum, rising like the moon “inter minora sidera,”
immediately absorbed all his attention. To the right and left dim
covered walks and parterres of flowers yielded soft glimpses of
shadow and a breeze of perfume as he moved along. At length he
arrived in front of the building. In the centre rose a vast dome, which,
together with the tall, slender minarets on both sides of it, was
supported by a range of beautiful arches, partly closed up by a wall,
and partly open. The façade of the structure consisted entirely of
marble, white like alabaster; and in the centre of the closed arches
were tablets of the same material, thickly inlaid with verses from the
Koran, wrought in black marble. The interior of the dome was
bordered, like the exterior, with white marble, thickly inlaid with
jasper, cornelian, and lapis lazuli, delicately disposed in the form of
flowers and other beautiful objects. The pavement was formed of
alternate squares of black and white marble, disposed with singular
art, and producing the finest effect imaginable upon the eye.
In the month of December, 1663, Aurungzebe, attended by his
whole court, and an army of ten thousand foot and thirty-five
thousand horse, undertook a journey into Cashmere, in the
pleasures of which, through the favour of Danekmend Khan, Bernier
was allowed to partake. Keeping as long as possible near the banks
of the Jumna, in order to enjoy by the way the pleasures of the
chase, and the salubrious waters of the river, the army proceeded
towards its place of destination by the way of Lahere. The style of
travelling adopted by the Great Mogul was perfectly unique. Two
sets of tents numerous and spacious enough to contain the whole of
the imperial retinue were provided, and of these one set was sent
forward, previous to the emperor’s setting out, to the spot marked
out for the first halting-place. Here the ground was levelled by the
pioneers, the tents pitched, and every convenience provided which
the luxurious effeminacy of oriental courtiers, and more particularly
of the fretful and capricious inmates of the harem, could require.
When the emperor arrived at his camp, a fresh body of pioneers and
labourers proceeded with the second set of tents, which they pitched
and prepared in like manner; and thus a kind of city, with all its
luxuries and conveniences, perpetually moved in advance of the
prince, and became stationary whenever and wherever he required
it.
During the journey Aurungzebe generally travelled in a species of
small turret or houdah, mounted on the back of an elephant. In fine
weather this houdah was open on all sides, that the inmate might
enjoy the cool breeze from whatever quarter of the heavens it might
blow; but when storms or showers came on, he closed his
casements, and reclined upon his couch, defended from all the
inclemencies of the weather as completely as in the apartments of
his palace. Ranchenara Begum, the sister of the emperor, and the
other great ladies of the harem, travelled in the same kind of moving
palace, mounted upon camels or elephants, and presented a
spectacle which Bernier delighted to contemplate. In general the
blinds or casements of these splendid little mansions of gold, scarlet,
and azure, were closed, to preserve the charms of those within from
“Phœbus’ amorous kisses,” or the profane gaze of the vulgar; but
once, as the gorgeous cavalcade moved along, our traveller caught
a glimpse of the interior of Ranchenara’s mikdembar, and beheld the
princess reclined within, while a little female slave fanned away the
dust and flies from her face with a bunch of peacock’s feathers. A
train of fifty or sixty elephants similarly, though less splendidly,
appointed, moving along with grave, solemn pace, surrounded by so
vast a retinue as that which now accompanied the court, appeared in
the eyes of our traveller to possess something truly royal in its
aspect, and with the beauteous goddesses which the fancy placed
within, seem, in spite of his affected philosophical indifference, to
have delighted him in a very extraordinary manner. True philosophy,
however, would have admired the show, while it condemned the
extravagance, and despised the pride and effeminacy which
produced it.
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

You might also like