Modern Python Cookbook - Programmer Books

2y ago
117 Views
36 Downloads
9.35 MB
819 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : River Barajas
Transcription

Modern Python CookbookThe latest in modern Python recipes for the busy modernprogrammerSteven F. LottBIRMINGHAM - MUMBAI

Modern Python CookbookCopyright 2016 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrieval system, ortransmitted in any form or by any means, without the prior written permission of thepublisher, 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 theinformation presented. However, the information contained in this book is sold withoutwarranty, either express or implied. Neither the author, nor Packt Publishing, and itsdealers and distributors will be held liable for any damages caused or alleged to be causeddirectly or indirectly by this book.Packt Publishing has endeavored to provide trademark information about all of thecompanies and products mentioned in this book by the appropriate use of capitals.However, Packt Publishing cannot guarantee the accuracy of this information.First published: November 2016Production reference: 1211116Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirminghamB3 2PB, UK.ISBN 978-1-78646-925-0www.packtpub.com

CreditsAuthorCopy EditorSteven F. LottSafis EditingReviewersProject CoordinatorSanjeev Kumar JaiswalDr. Vahid MirjaliliSuzanne CoutinhoCommissioning EditorProofreaderKunal ParikhSafis EditingAcquisition EditorIndexerSonali VernekarTejal Daruwale SoniContent Development EditorGraphicsZeeyan PinheiroKirk D'PenhaTechnical EditorsProduction CoordinatorPratish ShettyAbhishek SharmaAparna Bhagat

About the AuthorSteven F. Lott has been programming since the 70s, when computers were large, expensive,and rare. As a contract software developer and architect, he has worked on hundreds ofprojects, from very small to very large. He's been using Python to solve business problemsfor over 10 years.He’s currently leveraging Python to implement microservices and ETL pipelines. His othertitles with Packt Publishing include Python Essentials, Mastering Object-Oriented Python,Functional Python Programming, and Python for Secret Agents.Steven is currently a technomad who lives in various places on the east coast of the U.S. Histechnology blog is http://slott-softwarearchitect.blogspot.com and his LinkedInaddress is https://www.linkedin.com/in/steven-lott-029835.

About the ReviewersSanjeev Jaiswal is a computer graduate with 7 years of industrial experience in webdevelopment and cyber security. He basically uses Perl, Python, and GNU/Linux for hisday-to-day activities. He is currently working on projects involving penetration testing,source code review, and security design and implementations.He is very much interested in web and cloud security. You can follow him on Twitter at@aliencoders and on GitHub at https://github.com/jassics.He has written Instant PageSpeed Optimization and co-authored Learning Django WebDevelopment for Packt Publishing. He has reviewed more than 5 books for Packt Publishingand looks forward to authoring or reviewing more books for Packt Publishing and otherpublishers.Vahid Mirjalili is a software engineer and data scientist, currently working towards hisPhD study in Computer Science at Michigan State University. His research at the i-PRoBE(integrated pattern recognition and biometrics) lab involves attribute classification of faceimages from large image datasets.Furthermore, he teaches Python programming as well as computing concepts for dataanalysis and databases. Owing to his specialty in data mining, he is very interested inpredictive modeling and getting insights from data. He is also a Python developer and likesto contribute to the open source community.Moreover, he enjoys making tutorials for different directions of data science and computeralgorithms, which can be found in his GitHub repository at http://github.com/mirjalil/DataScience.

www.PacktPub.comFor support files and downloads related to your book, please visit www.PacktPub.com.Did you know that Packt offers eBook versions of every book published, with PDF andePub files available? You can upgrade to the eBook version at www.PacktPub.com and as aprint book customer, you are entitled to a discount on the eBook copy. Get in touch with usat service@packtpub.com for more details.At www.PacktPub.com, you can also read a collection of free technical articles, sign up for arange of free newsletters and receive exclusive discounts and offers on Packt books andeBooks.https://www.packtpub.com/maptGet the most in-demand software skills with Mapt. Mapt gives you full access to all Packtbooks and video courses, as well as industry-leading tools to help you plan your personaldevelopment and advance your career.Why subscribe?Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Table of ContentsPrefaceChapter 1: Numbers, Strings, and TuplesIntroductionCreating meaningful names and using variablesGetting readyHow to do it Choosing names wiselyAssigning names to objectsHow it works There's more See alsoWorking with large and small integersGetting readyHow to do it How it works There's more See alsoChoosing between float, decimal, and fractionGetting readyHow to do it Doing currency calculationsFraction calculationsFloating-point approximationsConverting numbers from one type to anotherHow it works There's more See alsoChoosing between true division and floor divisionGetting readyHow to do it Doing floor divisionDoing true divisionRational fraction calculationsHow it works See alsoRewriting an immutable 324252525262627272828

Getting readyHow to do it Slicing a piece of a stringUpdating a string with a replacementMaking a string all lowercaseRemoving extra punctuation marksHow it works There's more See alsoString parsing with regular expressionsGetting readyHow to do it How it works There's more See alsoBuilding complex strings with “template”.format()Getting readyHow to do it How it works There's more See alsoBuilding complex strings from lists of charactersGetting readyHow to do it How it works There's moreSee alsoUsing the Unicode characters that aren't on our keyboardsGetting readyHow to do it How it works See alsoEncoding strings – creating ASCII and UTF-8 bytesGetting readyHow to do it How it works See alsoDecoding bytes – how to get proper characters from some bytesGetting readyHow to do it.[ ii 4454646464747484949495051525253

How it works See alsoUsing tuples of itemsGetting readyHow to do it 54555555555656575858Creating tuplesExtracting items from a tupleHow it works There's moreSee also Chapter 2: Statements and Syntax59IntroductionWriting Python script and module files – syntax basicsGetting readyHow to do it How it works There's more See alsoWriting long lines of codeGetting readyHow to do it Using backslash to break a long statement into logical linesUsing the () characters to break a long statement into sensible piecesUsing string literal concatenationAssigning intermediate results to separate variablesHow it works There's more See alsoIncluding descriptions and documentationGetting readyHow to do it Writing docstrings for scriptsWriting docstrings for library modulesHow it works There's more See alsoWriting better RST markup in docstringsGetting readyHow to do it How it works [ iii 676767778

There's more Using directivesUsing inline markupSee alsoDesigning complex if elif chainsGetting readyHow to do it How it works There's more See alsoDesigning a while statement which terminates properlyGetting readyHow to do it How it works See alsoAvoiding a potential problem with break statementsGetting readyHow to do it How it works There's more See alsoLeveraging the exception matching rulesGetting readyHow to do it How it works There's more See alsoAvoiding a potential problem with an except: clauseGetting readyHow to do it How it works See alsoChaining exceptions with the raise from statementGetting readyHow to do it How it works There's more See alsoManaging a context using the with statementGetting ready[ iv 00100101102102102103103104104104105106107107107

How to do it How it works There's more See also108109110110Chapter 3: Function Definitions111IntroductionDesigning functions with optional parametersGetting readyHow to do it Particular to General DesignGeneral to Particular designHow it works There's more See alsoUsing super flexible keyword parametersGetting readyHow to do it How it works There's more See alsoForcing keyword-only arguments with the * separatorGetting readyHow to do it How it works There's more See alsoWriting explicit types on function parametersGetting readyHow to do it How it works There's more See alsoPicking an order for parameters based on partial functionsGetting readyHow to do it Wrapping a functionCreating a partial function with keyword parametersCreating a partial function with positional parametersHow it works There's more 35136137

See alsoWriting clear documentation strings with RST markupGetting readyHow to do it How it works There's more See alsoDesigning recursive functions around Python's stack limitsGetting readyHow to do it How it works There's more See alsoWriting reusable scripts with the script library switchGetting readyHow to do it How it works There's more See alsoChapter 4: Built-in Data Structures – list, set, dictIntroductionChoosing a data structureGetting readyHow to do it How it works There's more See alsoBuilding lists – literals, appending, and comprehensionsGetting readyHow to do it Building a list with the append() methodWriting a list comprehensionUsing the list function on a generator expressionHow it works There's more Other ways to extend a listSee alsoSlicing and dicing a listGetting ready[ vi 163163164165165165

How to do it How it works There's more See alsoDeleting from a list – deleting, removing, popping, and filteringGetting readyHow to do it Deleting items from a listThe remove() methodThe pop() methodThe filter() functionHow it works There's more See alsoReversing a copy of a listGetting readyHow to do it How it works See alsoUsing set methods and operatorsGetting readyHow to do it How it works There's more See alsoRemoving items from a set – remove(), pop(), and differenceGetting readyHow to do it How it works There's more See alsoCreating dictionaries – inserting and updatingGetting readyHow to do it How it works There's more See alsoRemoving from dictionaries – the pop() method and the del statementGetting readyHow to do it [ vii 191192192194194195196

How it works There's more See alsoControlling the order of dict keysGetting readyHow to do it How it works There's more See alsoHandling dictionaries and sets in doctest examplesGetting readyHow to do it How it works There's more Understanding variables, references, and assignmentHow to do it How it works There's more See alsoMaking shallow and deep copies of objectsGetting readyHow to do it How it works See alsoAvoiding mutable default values for function parametersGetting readyHow to do it How it works There's more See alsoChapter 5: User Inputs and OutputsIntroductionUsing features of the print() functionGetting readyHow to do it How it works There's more See alsoUsing input() and getpass() for user input[ viii 218220221222223223

Getting readyHow to do it How it works There's more Input string parsingInteraction via the cmd moduleSee alsoDebugging with “format”.format map(vars())Getting readyHow to do it How it works There's more See alsoUsing argparse to get command-line inputGetting readyHow to do it How it works There's more See alsoUsing cmd for creating command-line applicationsGetting readyHow to do it How it works There's more See alsoUsing the OS environment settingsGetting readyHow to do it How it works There's more See alsoChapter 6: Basics of Classes and ObjectsIntroductionUsing a class to encapsulate data and processingGetting readyHow to do it How it works There's more See also[ ix 254254255258259260

Designing classes with lots of processingGetting readyHow to do it How it works There's more See alsoDesigning classes with little unique processingGetting readyHow to do it Stateless objectsStateful objects with a new classStateful objects using an existing classHow it works There's more See alsoOptimizing small objects with slotsGetting readyHow to do it How it works There's more See alsoUsing more sophisticated collectionsGetting readyHow to do it How it works There's more See alsoExtending a collection – a list that does statisticsGetting readyHow to do it How it works There's more See alsoUsing properties for lazy attributesGetting ready How to do it How it works There's more See also Using settable properties to update eager 282284285286286286288290291291292

Getting readyHow to do it How it works There's more 292293296296296297298InitializationCalculationSee alsoChapter 7: More Advanced Class DesignIntroductionChoosing between inheritance and extension – the is-a questionGetting readyHow to do it Wrapping – aggregation and compositionExtending – inheritanceHow it works There's more See alsoSeparating concerns via multiple inheritanceGetting readyHow to do it How it works There's more See alsoLeveraging Python's duck typingGetting readyHow to do it How it works There's more See alsoManaging global and singleton objectsGetting readyHow to do it Module global variableClass-level static variableHow it works There's more Using more complex structures – maps of listsGetting readyHow to do it How it works [ xi 15316316318319319320320321321323324325325326326327

There's more See alsoCreating a class that has orderable objectsGetting readyHow to do it How it works There's more See alsoDefining an ordered collectionGetting readyHow to do it How it works There's more See alsoDeleting from a list of mappingsGetting readyHow to do it How it works There's more See alsoChapter 8: Functional and Reactive Programming FeaturesIntroductionWriting generator functions with the yield statementGetting readyHow to do it How it works There's more See alsoUsing stacked generator expressionsGetting readyHow to do it How it works There's more Namespace instead of listSee alsoApplying transformations to a collectionGetting ready How to do it How it works [ xii 367369369370372373

There's more See also Picking a subset – three ways to filterGetting ready How to do it How it works There's more See also Summarizing a collection – how to reduceGetting readyHow to do it How it works There's more Maxima and minimaPotential for abuseCombining map and reduce transformationsGetting readyHow to do it How it works There's more See alsoImplementing “there exists” processingGetting readyHow to do it How it works There's more The itertools moduleCreating a partial functionGetting readyHow to do it Using functools.partial()Creating a lambda objectHow it works There's more Simplifying complex algorithms with immutable data structuresGetting readyHow to do it How it works There's more Writing recursive generator functions with the yield from statement[ xiii 404406407410411412413

Getting readyHow to do it How it works There's more See also414416417417419Chapter 9: Input/Output, Physical Format, and Logical LayoutIntroductionUsing pathlib to work with filenamesGetting readyHow to do it Making the output filename by changing the input suffixMaking a number of sibling output files with distinct namesCreating a directory and a number of filesComparing file dates to see which is newerRemoving a fileFinding all files that match a given patternHow it works There's more See alsoReading and writing files with context managersGetting readyHow to do it How it works There's more See alsoReplacing a file while preserving the previous versionGetting readyHow to do it How it works There's more See alsoReading delimited files with the CSV moduleGetting readyHow to do it How it works There's more See alsoReading complex formats using regular expressionsGetting readyHow to do it [ xiv 447449

Defining the parse functionUsing the parse functionHow it works There's more See alsoReading JSON documentsGetting readyHow to do it How it works There's more Serializing a complex data structureDeserializing a complex data structureSee alsoReading XML documentsGetting readyHow to do it How it works There's more See alsoReading HTML documentsGetting readyHow to do it How it works There's more See alsoUpgrading CSV from DictReader to namedtuple readerGetting readyHow to do it How it works There's more See alsoUpgrading CSV from a DictReader to a namespace readerGetting readyHow to do it How it works There's more See alsoUsing multiple contexts for reading and writing filesGetting readyHow to do it [ xv 482483483485485485487

How it works There's more See also489490491Chapter 10: Statistical Programming and Linear RegressionIntroductionUsing the built-in statistics libraryGetting readyHow to do it How it works There's more Average of values in a CounterGetting readyHow to do it How it works There's more See alsoComputing the coefficient of a correlationGetting readyHow to do it How it works There's more Computing regression parametersGetting readyHow to do it How it works There's more Computing an autocorrelationGetting readyHow to do it How it works There's more Long-term modelSee alsoConfirming that the data is random – the null hypothesisGetting readyHow to do it How it works There's more See also[ xvi 530531532

Locating outliersGetting readyHow to do it How it works There's more See alsoAnalyzing many variables in one passGetting readyHow to do it How it works There's more Using map()See alsoChapter 11: ntroductionUsing docstrings for testingGetting readyHow to do it Writing examples for stateless functionsWriting examples for stateful objectsHow it works There's more See alsoTesting functions that raise exceptionsGetting readyHow to do it How it works There's more See alsoHandling common doctest issuesGetting readyHow to do it Writing doctest examples for mapping or set valuesWriting doctest examples for floating-point valuesHow it works There's more See alsoCreating separate test modules and packagesGetting readyHow to do it [ xvii 62564564565566566567568568570

How it works There's more Some other assertionsSeparate tests directorySee alsoCombining unittest and doctest testsGetting readyHow to do it How it works There's more See alsoTesting things

titles with Packt Publishing include Python Essentials, Mastering Object-Oriented Python, Functional Python Programming, and Python for Secret Agents. Steven is currently a technomad who lives in various places on the east coast of the U.S. His technology blog is . h. t t p ://s . l. o t t

Related Documents:

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

Related titles Essential System Administration Learning Python Linux Networking Cookbook Linux Security Cookbook Mac OS X for Unix Geeks Programming Python Python Cookbook Python in a Nutshell Unix in a Nutshell oreilly.com oreilly.com is more than a complete catalog ofO'Reilly books. You'll also find links to news, events, articles .

SAP has developed a new radio frequency (RF) concept. This RF cookbook helps developers to begin working in the RF framework. It answers frequently asked questions and helps to avoid common errors. This RF cookbook also provides some useful tips about the standard layout and screen structure that should be applied in the standard transactions.File Size: 299KBPage Count: 59Explore further[PDF] SAP EWM RF Cookbook - Free Download PDFdlscrib.comEWM RF Cookbook SAP blog of John Kristensenjksap.wordpress.comRF Cookbook - Part I Description - SAP Communityarchive.sap.comRF Cookbook - Part I Descriptiondocshare01.docshare.tipsSAP EWM RF Framework - SlideSharewww.slideshare.netRecommended to you based on what's popular Feedback

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

There are currently two versions of Python in use; Python 2 and Python 3. Python 3 is not backward compatible with Python 2. A lot of the imported modules were only available in Python 2 for quite some time, leading to a slow adoption of Python 3. However, this not really an issue anymore. Support for Python 2 will end in 2020.

PYTHON 39.95 ( 45.95 CDN) FAST! LEARN PYTHON—— PYTHON CRASH COURSE PYTHON CRASH COURSE MATTHES COVERS PYTHON 2 AND 3 Python Crash Course is a fast-paced, thorough intro-duction to programming with Python that will have you writing programs,