id
int64
0
25.6k
text
stringlengths
0
4.59k
17,800
your algorithms cannot assume that the entire data is in ram managing data becomes major task in itself using computer clusters or multicore machines becomes necessity and not luxury this will focus on this last piece of the puzzlehow to use multiple cores (either on the same machine or on separate machinesto speed up and organize your computations this will also be useful in other medium-sized data tasks using jug to break up your pipeline into tasks oftenwe have simple pipelinewe preprocess the initial datacompute featuresand then we need to call machine learning algorithm with the resulting features jug is package developed by luis pedro coelhoone of the authors of this book it is open source (using the liberal mit licenseand can be useful in many areas but was designed specifically around data analysis problems it simultaneously solves several problemsfor exampleit can memorize results to disk (or database)which means that if you ask it to compute something you have computed beforethe result is instead read from the disk it can use multiple cores or even multiple computers on cluster jug was also designed to work very well in batch computing environments that use queuing system such as portable batch system (pbs)the load sharing facility (lsf)or the oracle grid engine (ogeearlier known as sun grid enginethis will be used in the second half of the as we build online clusters and dispatch jobs to them about tasks tasks are the basic building block of jug task is just function and values for its argumentsfor exampledef double( )return *
17,801
task could be "call double with argument another task would be "call double with argument using jugswe can build these tasks as followsfrom jug import task task(double task(double save this to file called jugfile py (which is just regular python filenowwe can run jug execute to run the tasks this is something you run on the command linenot at the python promptinstead of python' jugfile py file (which should do nothing)you run jug execute you will also get some feedback on the tasks (jug will say that two tasks named "doublewere runrun jug execute again and it will tell you that it did nothingit does not need to in this casewe gained littlebut if the tasks took long time to computeit would be very useful you may notice that new directory named jugfile jugdata also appeared on your hard drivewith few other weirdly named files this is the memoization cache if you remove itjug execute will run all your tasks (both of themagain often it is good to distinguish between pure functionswhich simply take their inputs and return resultfrom more general functions that can perform actions such as reading from fileswriting to filesaccessing global variablesmodifying their argumentsor anything that the language allows some programming languagessuch as haskelleven have syntactic ways in which to distinguish pure from impure functions with jugyour tasks do not need to be perfectly pure it is even recommended that you use tasks to read your data or write your results howeveraccessing and modifying global variables will not work wellthe tasks may be run in any order in different processors the exceptions are global constantsbut even this may confuse the memoization system (if the value is changed between runssimilarlyyou should not modify the input values jug has debug mode (use jug execute--debug)which slows down your computationbut would give you useful error messages if you make this sort of mistake the preceding code works but it is bit cumbersomeyou are always repeating the task(functionargumentconstruct using bit of python magicwe can make the code even more naturalfrom jug import taskgenerator from time import sleep @taskgenerator def double( )
17,802
sleep( return * @taskgenerator def add(ab)return @taskgenerator def print_final_result(onamevalue)with open(oname' 'as outputprint >>output"final result:"value double( double(yy double( double( print_final_result('output txt'add( , )except for the use of taskgeneratorthe preceding code could have been standard python file howeverusing taskgeneratorit actually creates series of tasksand it is now possible to run it in way that takes advantage of multiple processors behind the scenesthe decorator transforms your functions so that they do not actually execute but create task we also take advantage of the fact that we can pass tasks to other tasks and this results in dependency being generated you may have noticed that we added few sleep( calls in the preceding code this simulates running long computation otherwisethis code is so fast that there is no point in using multiple processors we start by running jug statusnow we start two processes simultaneously (in the background)jug execute jug execute
17,803
now we run jug status againwe can see that the two initial double operators are running at the same time after about secondsthe whole process will finish and the output txt file will be written by the wayif your file was called anything other than jugfile pyyou would then have to specify it explicitly on the command linejug execute myfile py this is the only disadvantage of not using the name jugfile py by the way reusing partial results for examplelet' say you want to add new feature (or even set of featuresas we saw in computer vision-pattern recognition finding related poststhis can easily be done by changing the computation code feature howeverthis would imply recomputing all the features againwhich is wastefulparticularly if you want to test new features and techniques quickly@taskgenerator def new_features(im)import mahotas as mh im mh imread(fnameas_grey= es mh sobel(imjust_filter= return np array([np dot(es ravel()es ravel())]hfeatures as_array([hfeature(ffor in filenames]efeatures as_array([new_feature(ffor in filenames]features task(np hstack[hfeaturesefeatures]learning code now when you run jug execute againthe new features will be computedbut the old features will be loaded from the cache the logistic regression code will also be run again as those results also depend on the features and those are different now this is when jug can be very powerfulit ensures that you always get the results you want without wasteful overcomputation
17,804
looking under the hood how does jug workat the basic levelit is very simplea task is function plus its argument its arguments may be either values or other tasks if task takes other tasksthere is dependency between the two tasks (and the second one cannot be run until the results of the first task are availablebased on thisjug recursively computes hash for each task this hash value encodes the whole computation to get there when you run jug executethere is little loop as shown in the following code snippetfor in alltasksif has_not_run(and not backend_has_value( hash())value execute(save_to_backend(valuekey= hash()the real loop is much more complex because of locking issuesbut the general idea is the one that appears in the preceding code snippet the default backend writes the file to the disk (in this funny directory named jugfile jugdata/but another backend is available which uses redis database with proper lockingwhich jug takes care ofthis also allows for many processors to execute tasksthey will independently look at all the tasks and run the ones which have not run yet and then write them back to the shared backend this works on either the same machine (using multicore processorsor in multiple machines as long as they all have access to the same backend (for exampleusing network disk or the redis databasesin the next half of this we will discuss computer clustersbut for nowlet us focus on multiple cores you can also understand why it is able to memoize intermediate results if the backend already has the result of taskit is not run anymore on the other handif you change the taskeven in minute ways (by altering one of the parameters)its hash will change thereforeit will be recomputed furthermoreall tasks that depend on it will also have their hashes changed and they will be recomputed as well using jug for data analysis jug is generic frameworkbut it is ideally suited for medium-scale data analysis as you develop your analysis pipelineit is good to have intermediate results be saved if you already computed the preprocessing step before and are only changing the features you computeyou do not want to recompute the preprocessing if you already computed the features but want to try combining few new ones into the mixyou also do not want to recompute all your other features
17,805
jug is also specially optimized to work with numpy arrays sowhenever your tasks return or receive numpy arraysyou are taking advantage of this optimization jug is another piece of this ecosystem where everything works together we will now look back at computer vision-pattern recognition finding related posts we learned how to compute features on images remember that we were loading image filescomputing featurescombining thesenormalizing themand finally learning how to create classifier we are going to redo that exercise but this time with the use of jug the advantage of this version is that it is now possible to add new feature without having to recompute all of the previous versions we start with few imports as followsfrom jug import taskgenerator now we define the first task generatorthe feature computation@taskgenerator def hfeatures(fname)import mahotas as mh import numpy as np im mh imread(fnameas_grey= im mh stretch(imh mh features haralick(imreturn np hstack([ ptp( ) mean( )]note how we only imported numpy and mahotas inside the function this is small optimizationthis wayonly if the task is run are the modules loaded now we set up the image filenames as followsfilenames glob('dataset/jpg'we can use taskgenerator on any functioneven on the ones that we did not writesuch as numpy arrayimport numpy as np as_array taskgenerator(np arraycompute all featuresfeatures as_array([hfeature(ffor in filenames]get labels as an array as well labels map(label_forfres perform_cross_validation(featureslabels@taskgenerator
17,806
def write_result(ofnamevalue)with open(ofname' 'as outprint >>out"result is:"value write_result('output txt'resone small inconvenience of using jug is that we must always write functions to output the results to files as shown in the preceding examples this is small price to pay for the extra convenience of using jug not all features of jug could be mentioned in this but here is summary of the most potentially interesting ones that we didn' cover in the main textjug invalidatethis feature declares that all results from given function should be considered invalid and in need of recomputation this will also recompute any downstream computation that depended (even indirectlyon the invalidated results jug status --cacheif jug status takes too longyou can use the --cache flag to cache the status and speed it up note that this will not detect any changes to jugfile pybut you can always use --cache --clear to remove the cache and start again jug cleanupthis feature removes any extra files in the memoization cache this is garbage collection operation there are other more advanced featureswhich allow you to look at values that have been computed inside jugfile py read up on the use of "barriersin the jug documentation (online at rtfd orgusing amazon web services (awswhen you have lot of data and lot of computationyou might start to crave for more computing power amazon (aws amazon com/allows you to rent computing power by the hour thusyou can access large amount of computing power without having to precommit by purchasing large number of machines (including the costs of managing the infrastructurethere are other competitors in this marketbut amazon is the largest playerso we briefly cover it here amazon web services (awsis large set of services we will focus only on the elastic compute cluster (ec service this service offers you virtual machines and disk spacewhich can be allocated and deallocated quickly
17,807
there are three modes of usea reserved modewhereby you prepay to have cheaper per-hour accessa fixed per-hour rateand variable rate which depends on the overall compute market (when there is less demandthe costs are lowerwhen there is more demandthe prices go upfor testingyou can use single machine in the free tier this allows you to play around with the systemget used to the interfaceand so on howeverthis is very slow cpu machine thusdoing heavy computation using it is not advised on top of this general systemthere are several types of machines available with varying costsfrom single core to multicore system with lot of ramor even graphical processing units (gpuswe will later see that you can also get several of the cheaper machines and build yourself virtual cluster you can also choose to get linux or windows serverwith linux being slightly cheaper in this we will work our examples on linux but most of this information would be valid for windows machines as well the resources can be managed through web interface howeverit is also possible to do so programmatically and by setting up scripts which allocate virtual machinessetting up disksand all the operations that are possible through the web interface in factwhile the web interface changes very frequently (and some of the screenshots that we show in the book may be out-of-date by the time it goes to the press)the programmatic interface is more stable and the general architecture has remained stable since the service was introduced access to aws services is performed through traditional username/password systemalthough amazon calls the username an access key and the password secret key they probably do so to keep it separate from the username/password you use to access the web interface in factyou can create as many access/secret key pairs as you wish and give them different permissions this is helpful for larger team where senior user with access to the full web panel can create other keys for developers with less privileges amazon regions amazon com has several regions these correspond to physical regions of the worldwest coast east coast usseveral asian locationsa south american oneand european one if you will be transferring datait is best to keep it close to where you will be transferring to and from additionallyif you are handling user informationthere may be regulatory issues if you transfer it to another jurisdiction in that casedo check with an informed counsel on what the implications of transferring data about european customers to the us or vice versa are
17,808
amazon web services is very large topicand there are various books exclusively available which cover aws entirely the purpose of this is to give you an overall impression of what is available and what is possible with aws in the practical spirit of this bookwe do this by working through examplesbut we will not exhaust all possibilities creating your first machines the first step is to go to steps are similar to any other online service if you want to have more than single low-powered machineyou will need credit card in this examplewe will use few machinesso it may cost you few dollars if you want to run through it if you are not ready to take out credit card just yetyou can certainly read the to learn what aws provides without going through the examples then you can make more informed decision on whether to sign up once you sign up for aws and log inyou will be taken to the console here you will see the many services that aws provides
17,809
we pick and click on ec (the second element on the leftmost column--this panel is shown as it was when this book was writtenamazon regularly makes minor changesso you may see something slightly differentwe now see the ec management console as shown in the following screenshotin the top-right corneryou can pick your region (see the amazon regions information boxnote that you will only see information about the region that you have selected at the moment thusif you mistakenly select the wrong region (or have machines running in multiple regions)they may not appear (from casual conversations with other programmersthis seems to be common pitfall of using the ec web management console
17,810
in ec parlancea running server is called an instance so nowwe want to select launch instance nowfollow the classic wizard select the amazon linux option (if you are familiar with one of the other offered linux distributionssuch as red hatsuseor ubuntuyou can also select one of thosebut the configurations will be slightly differentwe will start with one instance of the micro type this is the smallest possible machineand it is free accept all of the defaults until you come to the screen mentioning key pairwe will pick the name awskeys for the key pair thenclick on the create download your key pair button to download the awskeys pem file save that file somewhere safethis is the secure shell (sshkey that will enable you to log in to your cloud machine accept the remaining defaults and your instance will launch you will now need to wait for about minute for your instance to come up eventuallythe instance will be shown in green with the status "running right-clicking on it and selecting the connect option will bring up instructions on how to connect the following will be standard ssh command of the formssh - awskeys pem ec -user@ec- - us-west- compute amazonaws com
17,811
thereforewe will be calling the ssh command and passing it the key files that we downloaded earlier as the identity (using the - optionwe are logging in as user ec -user at the machine with the address ec- - us-west- conompute amazonaws com this address willof coursebe different in your case if you choose another distribution for your instancethe username may also change in any casethe web panel will give you the correct information finallyif you are running an unix-style operating system (including mac os)you may have to tweak its permissions by calling the following codechmod awskeys pem this sets the read/write permission for the current user only ssh will otherwise give you an ugly warning nowyou should be able to log in to your machine if everything is okyou should see the banner as shown in the following screenshotthis is regular linux box where you have the sudo permissionyou can run any command as the super user by prefixing it with sudo you can run the update command it recommends to get your machine up to speed installing python packages on amazon linux if you preferred another distributionyou can use your knowledge of that distribution to install pythonnumpyand others herewe will do it on the standard amazon distribution we start by installing several basic python packages as followssudo yum - install python-devel python-dev python-pip numpy scipy python-matplotlib for compiling mahotaswe will also need +compilersudo yum - install gcc- +
17,812
in this systempip is installed as python-pip for conveniencewe will use pip to upgrade itself we will then use pip to install the necessary packagessudo pip-python install - pip sudo pip install scikit-learn jug mahotas at this pointyou can install any other package you like using pip running jug on our cloud machine we can now download the data and code from computer vision-pattern recognition finding related postsas followswget fixme-let' -build- -tar-gz-package tar xzf tar gz cd finallywe can do the followingjug execute this would work just finebut we would have to wait long time for the results our free tier machine (of type microis not very fast and it only has single processor so we will upgrade our machine we go back to the ec console and right-click on the running instance to get the pop-up menu we need to first stop the instance stopping an instance in virtual machine is equivalent to powering it off you can stop your machines at any time at that pointyou stop paying for them (you are still using disk spacewhich also has cost that is billed separatelyonce the machine is stoppedthe change instance type option becomes available now we can select more powerful instancefor examplea xlarge instancewhich has eight cores the machine is still offso you need to start it again (the virtual equivalent to booting upaws offers several instance types at different price points because this information is constantly being revised as more powerful options are introduced and prices are changed (generally getting cheaper)we cannot give you many details in this bookhoweveryou can find the most up-to-date information on amazon' website we need to wait for the instance to appear once again once it hasright-click on connect as described earlier to get the connection information as it will almost surely have changed when you change instance typesyour instance will get new address assigned to it
17,813
you can assign fixed ip to an instance using amazon' elastic ips functionalitywhich you will find on the left-hand side of the ec console this is useful if you find yourself creating and modifying instances very often there is small cost associated with this feature with eight coresyou can run eight jug processes simultaneouslyas illustrated in the following codejug execute jug execute (repeat to get jobs goinguse jug status to check whether these eight jobs are in fact running after your jobs are finished (which should now happen pretty fast)you can stop the machine and downgrade it again to micro instance to save moneythe micro instance is freewhile the extra large one costs dollars per hour (as of april --check the aws website for up-to-date informationautomating the generation of clusters with starcluster as we just learnedwe can spawn machines using the web interfacebut it quickly becomes tedious and error prone fortunatelyamazon has an api this means that we can write scripts which perform all the operations we discussed earlier automatically even betterothers have already developed tools which can be used for mechanizing and automating many of the processes you want to perform with aws group at mit developed exactly such tool called starcluster it happens to be python packageso you can install it with python toolssudo pip install starcluster you can run this from an amazon machine or from your local machine either option will work we will need to specify what our cluster will look like we do so by editing configuration file we generate template configuration file by running the following codestarcluster help thenpick the option for generating the configuration file in ~starclusterconfig once this is donewe will manually edit it
17,814
keyskeysand more keys there are three completely different types of keys that are important when dealing with awsa standard username/password combinationwhich you use to log in to the website the ssh key systemwhich is public/private key system implemented with fileswith your public key fileyou can log in to remote machines the aws access key/secret key systemwhich is just form of username/passwordwhich allows you to have multiple users on the same account (including adding different permissions to each onebut we will not cover those advanced features in this bookto look up our access/secret keyswe go back to the aws console and click on our name in the top-right cornerthen select security credentials now at the bottom of the screenthere should be our access key that may look something like aakiit hhf iusn ocaawhich we will use as an example in this now edit the configuration file this is standard ini filea text file where sections start by having their names in brackets and options are specified in the name=value format the first section is the aws info section and you should copy and paste your keys there[aws infoaws_access_key_id aakiit hhf iusn ocaa aws_secret_access_key nowwe come to the fun part that is defining cluster starcluster allows you to define as many different clusters as you wish the starting file has one called smallcluster it is defined in the cluster smallcluster section we will edit it to read as follows[cluster myclusterkeyname mykey cluster_size this changes the number of nodes to instead of the default of two we can additionally specify which type of instance each node will be and what the initial image is (rememberan image is the initial diskwhich defines what operating system you will be running and what software is installedstarcluster has few predefined imagesbut you can also build your own
17,815
we need to create new ssh key with the followingstarcluster createkey mykey - ssh/mykey rsa now that we have configured node cluster and set up the keyslet' try it out starcluster start mycluster this may take few minutes as it allocates new machines why when our cluster is only nodeswe always have master node all of these nodes have the same filesystemso anything we create on the master will also be seen by the slaves this also means that we can use jug on these clusters these clusters can be used as you wishbut they come pre-equipped with job queue enginewhich makes them ideal for batch processing the process of using them is simple you log in to the master node you prepare your scripts on the master (or better yethave them prepared before hand you submit jobs to the queue job can be any unix command the scheduler will find free nodes and run your job you wait for the jobs to finish you read the results on the master node you can also now kill all the slave nodes to save money in any casedo not forget that your system is running over the long term otherwisethis will cost you (in the dollars and cents meaning of the wordwe can log in to the master node with single commandstarcluster sshmaster mycluster we could also have looked up the address of the machine that was generated and used an ssh command as we did earlierbut when using the preceding commandit does not matter what the address wasas starcluster takes care of it behind the scenes for us as we said earlierstarcluster provides batch queuing system for its clustersyou write script to perform your actionsput it on the queueand it will run in any available node at this pointyou will need to repeat the actions to install the needed packages on the cluster if this was real projectwe would set up script to perform all the initialization for usbut since it is tutorialyou should just run the installation steps again
17,816
we can use the same jugfile py system as beforeexcept that nowinstead of running it directly on the masterwe schedule it on the cluster firstwrite very simple wrapper script#!/usr/bin/env bash jug execute jugfile py call it using run-jugfile sh and use chmod + run-jugfile sh to give it an executable permissionfor in 'seq 'do qsub run-jugfile shdone this will create jobseach of which will run the run-jugfile sh scriptwhich will simply call jug you can still use the master as you wish in particularyou can at any moment run jug status and see the status of the computation in factjug was developed in exactly such an environmentso it works very well in it eventuallythe computation will be finished and we can kill off all the nodes be sure to save the desired results somewhere and run the followingstarcluster terminate mycluster note that terminating will really destroy the filesystem and all your results of courseit is possible to change this default you can have the cluster write to filesystem which is not allocated and destroyed by starcluster but is available to you on regular instancein fact the flexibility of these tools is immense howeverthese advanced manipulations could not all fit in this starcluster has excellent documentation online at which you should read for more information about all the possibilities of this tool we have seen only small fraction of the functionality and used only the default settings here
17,817
summary we saw how to use juga little python frameworkto manage computations in way that takes advantage of multiple cores or multiple machines although this framework is genericit was built specifically to address the data analysis needs of its author (who is also an author of this bookthereforeit has several aspects that make it fit in with the rest of the python machine learning environment we also learned about awsthe amazon cloud using cloud computing is often more effective use of resources than building an in-house computing capacity this is particularly true if your needs are not constantbut changing starcluster even allows for clusters that automatically grow as you launch more jobs and shrink as they terminate this is the end of the book we have come long way we learned how to perform classification when we have labeled data and clustering when we do not we learned about dimensionality reduction and topic modeling to make sense of large datasets towards the endwe looked at some specific applicationssuch as music genre classification and computer vision for implementationswe relied on python this language has an increasingly expanding ecosystem of numeric computing packages built on top of numpy whenever possiblewe relied on scikit-learn but also used other packages when necessary due to the fact that they all use the same basic data structure (the numpy multidimensional array)it is possible to mix functionality from different packages seamlessly all of the packages used in this book are open source and available for use in any project naturallywe did not cover every machine learning topic in the appendixwhere to learn more about machine learningwe provide pointers to selection of other resources that will help interested readers learn more about machine learning
17,818
about machine learning we are at the end of our book and now take moment to look at what else is out there that could be useful for our readers there are many wonderful resources out there to learn more about machine learning (way too much to cover them all hereour list can therefore represent only small and very biased sampling of the resources we think are best at the time of writing online courses andrew ng is professor at stanford who runs an online course in machine learning as massive open online course (moocat coursera (orgit is free of chargebut may represent significant investment of time and effort (return on investment guaranteed!books this book focused on the practical side of machine learning we did not present the thinking behind the algorithms or the theory that justifies them if you are interested in that aspect of machine learningthen we recommend pattern recognition and machine learningc bishop springer apply italics to this this is classical introductory text in the field it will teach you the nitty-gritties of most of the algorithms we used in this book
17,819
if you want to move beyond an introduction and learn all the gory mathematical detailsthen machine learninga probabilistic perspectivek murphythe mit pressis an excellent option it is very recent (published in )and contains the cutting edge of ml research this , page book can also serve as referenceas very little of machine learning has been left out & sites the following are the two & websites of machine learningmetaoptimize ( & website where many very knowledgeable researchers and practitioners interact cross validated (statistics & sitewhich often features machine learning questions as well as mentioned in the beginning of the bookif you have questions specific to particular parts of the bookfeel free to ask them at twotoreal (jump in and help as best as we can blogs the following is an obviously non-exhaustive list of blogs that are interesting to someone working on machine learningmachine learning theory at degdeg this is blog by john langfordthe brain behind vowpal wabbit (degdeg the average pace is approximately one post per month the posts are more theoretical they also offer additional value in brain teasers text and data mining by practical means at blogspot de degdeg the average pace is one per monthwhich is very practical and has always surprising approaches blog by edwin chen at degdeg the average pace is one per monthproviding more applied topics
17,820
machined learnings at degdeg flowingdata at degdeg the average pace is one per monthcovering theoretical discussions of practical problems although being more of statistics blogthe posts often intersect with machine learning simply statistics at degdeg the average pace is one per daywith the posts revolving more around statistics normal deviate at degdeg the average pace is one per monthproviding more applied topicsoften revolving around learning big data there are several posts per monthfocusing on statistics and big data statistical modelingcausal inferenceand social science at andrewgelman com degdeg there is one post per day with often funny reads when the author points out flaws in popular media using statistics data sources if you want to play around with algorithmsyou can obtain many datasets from the machine learning repository at university of california at irvine (uciyou can find it at getting competitive an excellent way to learn more about machine learning is by trying out competitionkaggle (and has already been mentioned in the introduction on the websiteyou will find several different competitions with different structures and often cash prizes the supervised learning competitions almost always follow the following formatyou (and every other competitorare given access to labeled training data and testing data (without labelsyour task is to submit predictions for the testing data when the competition closeswhoever has the best accuracy wins the prizes range from glory to cash
17,821
of coursewinning something is nicebut you can gain lot of useful experience just by participating soyou have to stay tunedespecially after the competition is over and participants start sharing their approaches in the forum most of the timewinning is not about developing new algorithmit is about cleverly preprocessingnormalizingand combining the existing methods what was left out we did not cover every machine learning package available for python given the limited spacewe chose to focus on scikit-learn howeverthere are other optionsand we list few of them heremodular toolkit for data processing (mdp at pybrain at machine learning toolkit (milkat sourceforge net milk degdeg this package was developed by one of the authors of this bookand covers some algorithms and techniques that are not included in scikit-learn more general resource is at source machine learning software as is usually the case with repositories such as this onethe quality varies between excellentwell-maintained software and projects that were one-offs and then abandoned it may be worth checking out if your problem is very specific and none of the more general packages address it summary we are now truly at the end we hope you have enjoyed the book and feel well equipped to start your own machine learning adventure we also hope you have learned the importance of carefully testing your methodsin particularof using correct cross-validation and not reporting training test resultswhich are an over-inflated estimate of how good your method really is
17,822
acceptedanswerid attribute additive smoothing add-one smoothing advanced baskets analysis amazon linux python packagesinstalling on amazon regions amazon web services see aws apriori algorithm area under curve (auc as keypoint detection associated press (ap association rule mining - association rules attributes preselecting processing auditory filterbank temporal envelope (afte automatic music genre classification (amgc aws machinecreating - using bag-of-word approach about challenges bag-of-word approachchallenges about less important wordsremoving raw textconverting into bag-of-words stemming stop wordson steroids word count vectorsnormalizing wordscounting - basic image processing about filteringfor different effects gaussian blurring thresholding - basket analysis about association rule mining - supermarket shopping basketsanalyzing - useful predictionsobtaining beer and diapers story bernoullinb bias-variance about trade-off big data expression binary classification binary matrix of recommendations using - blogsmachine language body attribute classification about naive bayesusing for - poor answersdetecting
17,823
building evaluating - loss function search procedure structure classification performance improvingwith mel frequency cepstral coefficients - classifier buildingfft used classesusing creating - integratinginto site parameterstuning - performanceimproving performancemeasuring slimming training classifierclassy answers tuning classifier performance measuringreceiver operator characteristic (rocused classifier performanceimproving bias-variance high biasfixing high bias or low bias - high variancefixing classy answers classifiertuning classifying instancetuning cloud machine jugrunning on cluster generation automatingwith starcluster - clustering about flat clustering hierarchical clustering kmeans algorithm - test dataobtaining for idea evaluation - cluster package commentcount attribute complex classifiers building complex dataset computer vision confusion matrix usedfor accuracy measurement in multiclass problems - constants package correlation about using - cost function countvectorizer coursera url creationdate attribute cross validated about url cross-validation cross-validationfor regression cross-validation schedule data fetching slimming downto chewable chunks data analysis jugusing for - datamachine learning application cleaning preprocessing reading data sourcesmachine language dimensionality reduction dot(function elastic net model elastic nets usingin scikit-learn ensemble learning enthought python distribution url
17,824
false negative false positive fast fourier transform see fft fast fourier transformation feature engineering feature extraction about lda pca features about computingfrom images designing - engineering selecting writing - feature selection feature selection methods fft usedfor building classifier fftpack package filtering for different effects filters disadvantage usedfor detecting features fit_transform(method flat clustering gaussian blurring gaussiannb genfromtxt(function gensim package good answers defining graphical processing units (gpus gtzan dataset about urlfor downloading haralick texture features harder dataset classifying hierarchical clustering hierarchical dirichlet process (hdp house prices predictingwith regression - hyperparameters setting image analysis image processing images displaying featurescomputing from loading indexingnumpy installationpython installationpython packages on amazon linux instance instanceclassy answers tuning integrate package interest point detection international society formusic information retrieval (ismir interpolate package io package iris dataset about visualization jpeg jug about partial resultsreusing runningon cloud machine urlfor documentation used for breaking up pipelineinto tasks usingfor data analysis - working jug cleanup
17,825
jugfile jugdata directory jugfile py file jug invalidate jug status --cache kaggle url keys kmeans - -means clustering -nearest neighbor (knnalgorithm labels laplace smoothing lasso about usingin scikit-learn latent dirichlet allocation (lda learning algorithm selecting - levenshtein distance lidstone smoothing lift linalg package linear discriminant analysis (lda linearregression class load sharing facility (lsf local feature representations - logistic regression applyingto postclassification problem example using logistic regression classifier loss function machine learning application about datacleaning datapreprocessing datareading learning algorithmselecting - machine learning (mlabout additional resources blogs books data sources goals in real world online courses & sites supervised learning competitions machine learning repository machine learning toolkit (milkurl machines creating - mahotas mahotas computer vision package mahotas features massive open online course (mooc matplotlib about url matshow(function maxentropy package mds - mel frequency cepstral coefficients usedfor improving classification performance - mel frequency cepstral coefficients (mfcc mel frequency cepstrum (mfc metaoptimize about url metaoptimized mfcc(function mh features haralick function mlcomp url modular toolkit for data processing (mdpurl movie recommendation dataset about
17,826
using movie neighborsviewing multiple methodscombining - mp files convertinginto wave format multiclass classification multiclass problems confusion matrixused for accuracy measurement - multidimensional regression multidimensional scaling see mds multinomialnb music decomposinginto sine wave components music data fetching music information retrieval (mir numpy about indexing learning - non-existing valueshandling runtime behaviorscomparing urlfor tutorials odr package opencv opinion mining optimize package oracle grid engine (oge ordinary least squares (olsregression otsu threshold overfitting owneruserid attribute naive bayes usedfor classification - naive bayes classifier about - accountingfor arithmetic underflows - accountingfor oddities accountingfor unseen words naive bayes classifiers bernoullinb gaussiannb multinomialnb natural language toolkit see nltk ndimage ( -dimensional image ndimage package nearest neighbor classification - nearest neighbor search (nns netflix nltk installing using nltk' stemmer usedfor extending vectorizer norm(function np linalg lstsq function packagesscipy cluster constants fftpack integrate interpolate io linalg maxentropy ndimage odr optimize signal sparse spatial special stats parameters tweaking partial results reusing part of speech (pos pattern recognition pca about applying
17,827
sketching pearsonr(function penalized regression elastic net penalty penalty lasso model penn treebank project url greater than scenarios about hyperparameterssetting predictionrating - recommendationsrating - text example png polyfit(function portable batch system (pbs postclassification problem logistic regressionapplying to posts clustering relatednessmeasuring posttype attribute principal component analysis see pca pybrain url pymining pyplot package python about installing python packages installingon amazon linux & sites about cross validated metaoptimize read_fft(function receiver operator characteristic (rocabout usedfor measuring classifier performance redundant features detectingfilters used redundant features detection correlationusing - mutual information - regression usedfor predicting house prices - ridge regression ridley-calvard method root mean squared error (rmse salt and pepper noise adding centerinserting in focus - save(function scale-invariant feature transform see sift scikit scikit-image (skimage scikit-learn elastic netsusing in lassousing in scipy about packages url score attribute secure shell (ssh securities and exchange commission (sec seeds dataset sentiment analysistweet sentiwordnet about url usedfor cheating sift signal package similarity comparingin topic space - sine wave components musicdecomposing into - sklearn feature_selection package sklearn lda
17,828
for paula,thomas and his brother on the way lib fl ff
17,829
introduction part ithe python language tutorial introduction lexical conventions and syntax types and objects operators and expressions program structure and control flow functions and functional programming classes and object-oriented programming modulespackagesand distribution input and output execution environment testingdebuggingprofilingand tuning part iithe python library built-in functions python runtime services mathematics data structuresalgorithmsand code simplification string and text handling python database access file and directory handling operating system services threads and concurrency network programming and sockets internet application programming web programming internet data handling and encoding miscellaneous library modules part iiiextending and embedding extending and embedding python appendixpython index lib fl ff
17,830
introduction ithe python language tutorial introduction running python variables and arithmetic expressions conditionals file input and output strings lists tuples sets dictionaries iteration and looping functions generators coroutines objects and classes exceptions modules getting help lexical conventions and syntax line structure and indentation identifiers and reserved words numeric literals string literals containers operatorsdelimitersand special symbols documentation strings decorators source code encoding types and objects terminology object identity and type reference counting and garbage collection references and copies lib fl ff
17,831
contents first-class objects built-in types for representing data the none type numeric types sequence types mapping types set types built-in types for representing program structure callable types classestypesand instances modules built-in types for interpreter internals code objects frame objects traceback objects generator objects slice objects ellipsis object object behavior and special methods object creation and destruction object string representation object comparison and ordering type checking attribute access attribute wrapping and descriptors sequence and mapping methods iteration mathematical operations callable interface context management protocol object inspection and dir( operators and expressions operations on numbers operations on sequences string formatting advanced string formatting operations on dictionaries operations on sets augmented assignment lib fl ff
17,832
the attribute operator the function call (operator conversion functions boolean expressions and truth values object equality and identity order of evaluation conditional expressions program structure and control flow program structure and execution conditional execution loops and iteration exceptions built-in exceptions defining new exceptions context managers and the with statement assertions and _debug_ parameter passing and return values scoping rules functions as objects and closures generators and yield coroutines and yield expressions using generators and coroutines list comprehensions generator expressions declarative programming the lambda operator recursion functions and functional programming functions decorators documentation strings function attributes eval()exec()and compile( classes and object-oriented programming the class statement class instances scoping rules inheritance ix lib fl ff
17,833
contents polymorphism dynamic binding and duck typing static methods and class methods properties descriptors data encapsulation and private attributes object memory management object representation and attribute binding _slots_ operator overloading types and class membership tests abstract base classes metaclasses class decorators modulespackagesand distribution modules and the import statement importing selected symbols from module execution as the main program the module search path module loading and compilation module reloading and unloading packages distributing python programs and libraries installing third-party libraries environment variables files and file objects standard inputoutputand error the print statement the print(function variable interpolation in text output generating output input and output reading command-line options unicode string handling unicode / unicode data encodings unicode character properties object persistence and the pickle module lib fl ff
17,834
execution environment interpreter options and environment interactive sessions xi launching python applications site configuration files per-user site packages enabling future features program termination testingdebuggingprofilingand tuning documentation strings and the doctest module unit testing and the unittest module the python debugger and the pdb module debugger commands debugging from the command line configuring the debugger program profiling tuning and optimization making timing measurements making memory measurements disassembly tuning strategies iithe python library built-in functions and exceptions built-in functions and types built-in exceptions exception base classes exception instances predefined exception classes built-in warnings future_builtins python runtime services atexit copy notes lib fl ff
17,835
xii gc notes inspect marshal notes pickle notes sys variables functions traceback types notes warnings notes weakref example notes mathematics decimal decimal objects context objects functions and constants examples notes fractions math notes numbers notes random seeding and initialization random integers random sequences real-valued random distributions notes lib fl ff
17,836
data structuresalgorithmsand code simplification abc array xiii notes bisect collections deque and defaultdict named tuples abstract base classes contextlib functools heapq itertools examples operator string and text handling codecs low-level codecs interface / -related functions useful constants standard encodings re notes pattern syntax functions regular expression objects match objects example notes string constants formatter objects template strings utility functions struct packing and unpacking functions struct objects lib fl ff
17,837
xiv format codes notes unicodedata python database access relational database api specification connections cursors forming queries type objects error handling multithreading mapping results into dictionaries database api extensions sqlite module module-level functions connection objects cursors and basic operations dbm-style database modules shelve module file and directory handling bz filecmp fnmatch examples example gzip glob notes shutil tarfile exceptions example tempfile zipfile zlib lib fl ff
17,838
operating system services commands notes xv configparserconfigparser the configparser class example notes datetime date objects time objects datetime objects timedelta objects mathematical operations involving dates tzinfo objects date and time parsing errno posix error codes windows error codes fcntl example notes io base / interface raw / buffered binary / text / the open(function abstract base classes logging logging levels basic configuration logger objects handler objects message formatting miscellaneous utility functions logging configuration performance considerations notes lib fl ff
17,839
contents mmap notes msvcrt optparse example notes os process environment file creation and file descriptors files and directories process management system configuration exceptions os path signal example notes subprocess examples notes time notes winreg notes threads and concurrency basic concepts concurrent programming and python multiprocessing processes interprocess communication process pools shared data and synchronization managed objects connections miscellaneous utility functions general advice on multiprocessing threading thread objects timer objects lib fl ff
17,840
lock objects rlock xvii semaphore and bounded semaphore events condition variables working with locks thread termination and suspension utility functions the global interpreter lock programming with threads queuequeue queue example with threads coroutines and microthreading network programming and sockets network programming basics asynchat asyncore example select advanced module features advanced asynchronous / example when to consider asynchronous networking socket address families socket types addressing functions exceptions example notes ssl examples socketserver handlers servers defining customized servers customization of application servers lib fl ff
17,841
xviii internet application programming ftplib example http package http client (httplib http server (basehttpservercgihttpserversimplehttpserver http cookies (cookie http cookiejar (cookielibsmtplib example urllib package urllib request (urllib urllib response urllib parse urllib error urllib robotparser (robotparser notes xmlrpc package xmlrpc client (xmlrpclib xmlrpc server (simplexmlrpcserverdocxmlrpcserver web programming cgi cgi programming advice notes cgitb wsgiref the wsgi specification wsgiref package webbrowser internet data handling and encoding base binascii csv dialects example lib fl ff
17,842
email package xix parsing email composing email notes hashlib hmac example htmlparser example mimetypes json quopri xml package xml example document xml dom minidom xml etree elementtree xml sax xml sax saxutils miscellaneous library modules python services string processing operating system modules network internet data handling internationalization multimedia services miscellaneous iiiextending and embedding extending and embedding python extension modules an extension module prototype naming extension modules compiling and packaging extensions type conversion from python to type conversion from to python lib fl ff
17,843
contents adding values to module error handling reference counting threads embedding the python interpreter an embedding template compilation and linking basic interpreter operation and setup accessing python from converting python objects to ctypes loading shared libraries foreign functions datatypes calling foreign functions alternative type construction methods utility functions example advanced extending and embedding jython and ironpython appendix python who should be using python new language features source code encoding and identifiers set literals set and dictionary comprehensions extended iterable unpacking nonlocal variables function annotations keyword-only arguments ellipsis as an expression chained exceptions improved super( advanced metaclasses common pitfalls text versus bytes new / system lib fl ff
17,844
print(and exec(functions use of iterators and views integers and integer division comparisons xxi iterators and generators file namesargumentsand environment variables library reorganization absolute imports code migration and to porting code to python providing test coverage using the to tool practical porting strategy simultaneous python and python support participate index lib fl ff
17,845
david beazley is long-time python enthusiasthaving been involved with the python community since he is probably best known for his work on swiga popular software package for integrating / +programs with other programming languagesincluding pythonperlruby,tcland java he has also written number of other programming toolsincluding plya python implementation of lex and yacc dave spent seven years working in the theoretical physics division at los alamos national laboratorywhere he helped pioneer the use of python with massively parallel supercomputers after thatdave went off to work as an evil professorwhere he enjoyed tormenting college students with variety of insane programming projects howeverhe has since seen the error of his ways and is now working as an independent software developerconsultantpython trainerand occasional jazz musician living in chicago he can be contacted at about the technical editor noah gift is the co-author of python for unix and linux system administration ( 'reillyand is also working on google app engine in action (manninghe is an authorspeakerconsultantand community leaderwriting for publications such as ibm developerworksred hat magazineo'reillyand mactech his consulting company' website is noah has master' degree in cis from cal statelos angelesa in nutritional science from cal poly san luis obispois an apple and lpi-certified sysadminand has worked at companies such as caltechdisney feature animationsony imageworksand turner studios he is currently working at weta digital in new zealand in his free time he enjoys spending time with his wife leah and their son liamcomposing for the pianorunning marathonsand exercising religiously lib fl ff
17,846
this book would not be possible without the support of many people first and foremosti' like to thank noah gift for jumping into the project and providing his amazing feedback on the fourth edition kurt grandis also provided useful comments for many ' also like to acknowledge past technical reviewers timothy boronczykpaul duboismats wichmanndavid ascherand tim bell for their valuable comments and advice that made earlier editions success guido van rossumjeremy hyltonfred drakeroger masseand barry warsaw also provided tremendous assistance with the first edition while hosting me for few weeks back in the hot summer of lastbut not leastthis book would not be possible without all of the feedback received from readers there are far too many people to list individuallybut have done my best to incorporate your suggestions for making the book even better ' also like to thank all the folks at addison-wesley and pearson education for their continued commitment to the project and assistance mark tabermichael thurstonseth kerneyand lisa thibault all helped out to get this edition out the door in good shape special thanks is in order for robin drakewhose tremendous effort in editing previous editions made the third edition possible finallyi' like to acknowledge my amazing wife and partner paula kamen for all of her encouragementdiabolical humorand love lib fl ff
17,847
as the reader of this bookyou are our most important critic and commentator we value your opinion and want to know what we're doing rightwhat we could do betterwhat areas you' like to see us publish inand any other words of wisdom you're willing to pass our way you can email or write me directly to let me know what you did or didn' like about this book--as well as what we can do to make our books stronger please note that cannot help you with technical problems related to the topic of this bookand that due to the high volume of mail receivei might not be able to reply to every message when you writeplease be sure to include this book' title and author as well as your name and phone or email address will carefully review your comments and share them with the author and editors who worked on the book emailmailfeedback@developers-library info mark taber associate publisher pearson education east th street indianapolisin usa reader services visit our website and register this book at informit com/register for convenient access to any updatesdownloadsor errata that might be available for this book lib fl ff
17,848
his book is intended to be concise reference to the python programming language although an experienced programmer will probably be able to learn python from this bookit' not intended to be an extended tutorial or treatise on how to program ratherthe goal is to present the core python languageand the most essential parts of the python library in manner that' accurate and concise this book assumes that the reader has prior programming experience with python or another language such as or java in additiona general familiarity with systems programming topics (for examplebasic operating system concepts and network programmingmay be useful in understanding certain parts of the library reference python is freely available for download at additionthe python website includes links to documentationhow-to guidesand wide assortment of third-party software this edition of python essential reference comes at pivotal time in python' evolution python and python are being released almost simultaneously yetpython is release that breaks backwards compatibility with prior python versions as an author and programmeri' faced with dilemmado simply jump forward to python or do build upon the python releases that are more familiar to most programmersyears agoas programmer used to treat certain books as the ultimate authority on what programming language features should be used for exampleif you were using something that wasn' documented in the & bookit probably wasn' going to be portable and should be approached with caution this approach served me very well as programmer and it' the approach have decided to take in this edition of the essential reference namelyi have chosen to omit features of python that have been removed from python likewisei don' focus on features of python that have not been back-ported (although such features are still covered in an appendixas resulti hope this book can be useful companion for python programmersregardless of what python version is being used the fourth edition of python essential reference also includes some of the most exciting changes since its initial publication nearly ten years ago much of python' development throughout the last few years has focused on new programming language features--especially related to functional and meta programming as resultthe on functions and object-oriented programming have been greatly expanded to cover topics such as generatorsiteratorscoroutinesdecoratorsand metaclasses the library have been updated to focus on more modern modules examples and code fragments have also been updated throughout the book think most programmers will be quite pleased with the expanded coverage finallyit should be noted that python already includes thousands of pages of useful documentation the contents of this book are largely based on that documentationbut with number of key differences firstthis reference presents information in much more compact formwith different examples and alternative descriptions of many topics seconda significant number of topics in the library reference have been expanded lib fl ff
17,849
introduction to include outside reference material this is especially true for low-level system and networking modules in which effective use of module normally relies on myriad of options listed in manuals and outside references in additionin order to produce more concise referencea number of deprecated and relatively obscure library modules have been omitted in writing this bookit has been my goal to produce reference containing virtually everything have needed to use python and its large collection of modules although this is by no means gentle introduction to the python languagei hope that you find the contents of this book to be useful addition to your programming reference library for many years to come welcome your comments david beazley chicagoillinois june lib fl ff
17,850
the python language tutorial introduction lexical conventions and syntax types and objects operators and expressions program structure and control flow functions and functional programming classes and object-oriented programming modulespackagesand distribution input and output execution environment testingdebuggingprofilingand tuning lib fl ff
17,851
lib fl ff
17,852
tutorial introduction his provides quick introduction to python the goal is to illustrate most of python' essential features without getting too bogged down in special rules or details to do thisthe briefly covers basic concepts such as variablesexpressionscontrol flowfunctionsgeneratorsclassesand input/output this is not intended to provide comprehensive coverage howeverexperienced programmers should be able to extrapolate from the material in this to create more advanced programs beginners are encouraged to try few examples to get feel for the language if you are new to python and using python you might want to follow this using python instead virtually all the major concepts apply to both versionsbut there are small number of critical syntax changes in python --mostly related to printing and / --that might break many of the examples shown in this section please refer to appendix "python ,for further details running python python programs are executed by an interpreter usuallythe interpreter is started by simply typing python into command shell howeverthere are many different implementations of the interpreter and python development environments (for examplejythonironpythonidleactivepython,wing idepydevetc )so you should consult the documentation for startup details when the interpreter startsa prompt appears at which you can start typing programs into simple read-evaluation loop for examplein the following outputthe interpreter displays its copyright message and presents the user with the promptat which the user types the familiar "hello worldcommandpython rc ( rc : sep : : [gcc (apple inc build )on darwin type "help""copyright""creditsor "licensefor more information print "hello worldhello world lib fl ff
17,853
tutorial introduction note if you try the preceding example and it fails with syntaxerroryou are probably using python if this is the caseyou can continue to follow along with this but be aware that the print statement turned into function in python simply add parentheses around the items to be printed in the examples that follow for instanceprint("hello world"hello world putting parentheses around the item to be printed also works in python as long as you are printing just single item howeverit' not syntax that you commonly see in existing python code in later this syntax is sometimes used in examples in which the primary focus is feature not directly related to printingbut where the example is supposed to work with both python and python' interactive mode is one of its most useful features in the interactive shellyou can type any valid statement or sequence of statements and immediately view the results many peopleincluding the authoreven use interactive python as their desktop calculator for example when you use python interactivelythe special variable holds the result of the last operation this can be useful if you want to save or use the result of the last operation in subsequent statements howeverit' important to stress that this variable is only defined when working interactively if you want to create program that you can run repeatedlyput statements in file such as the followinghelloworld py print "hello worldpython source files are ordinary text files and normally have py suffix the character denotes comment that extends to the end of the line to execute the helloworld py fileyou provide the filename to the interpreter as followspython helloworld py hello world on windowspython programs can be started by double-clicking py file or typing the name of the program into the run command on the windows start menu this launches the interpreter and runs the program in console window howeverbe aware that the console window will disappear immediately after the program completes its execution (often before you can read its outputfor debuggingit is better to run the program within python development tool such as idle on unixyou can use #on the first line of the programlike this#!/usr/bin/env python print "hello worldf lib fl ff
17,854
the interpreter runs statements until it reaches the end of the input file if it' running interactivelyyou can exit the interpreter by typing the eof (end of filecharacter or by selecting exit from pull-down menu of python ide on unixeof is ctrl+don windowsit' ctrl+ program can request to exit by raising the systemexit exception raise systemexit variables and arithmetic expressions the program in listing shows the use of variables and expressions by performing simple compound-interest calculation listing simple compound-interest calculation principal initial amount rate interest rate numyears number of years year while year <numyearsprincipal principal ( rateprint yearprincipal reminderprint(yearprincipalin python year + the output of this program is the following table python is dynamically typed language where variable names are bound to different valuespossibly of varying typesduring program execution the assignment operator simply creates an association between name and value although each value has an associated type such as an integer or stringvariable names are untyped and can be made to refer to any type of data during execution this is different from cfor examplein which name represents fixed typesizeand location in memory into which value is stored the dynamic behavior of python can be seen in listing with the principal variable initiallyit' assigned to an integer value howeverlater in the program it' reassigned as followsprincipal principal ( ratethis statement evaluates the expression and reassociates the name principal with the result although the original value of principal was an integer the new value is now floating-point number (rate is defined as floatso the value of the above expression is also floatthusthe apparent "typeof principal dynamically changes from an integer to float in the middle of the program howeverto be preciseit' not the type of principal that has changedbut rather the value to which the principal name refers newline terminates each statement howeveryou can use semicolon to separate statements on the same lineas shown hereprincipal rate numyears lib fl ff
17,855
tutorial introduction the while statement tests the conditional expression that immediately follows if the tested statement is truethe body of the while statement executes the condition is then retested and the body executed again until the condition becomes false because the body of the loop is denoted by indentationthe three statements following while in listing execute on each iteration python doesn' specify the amount of required indentationas long as it' consistent within block howeverit is most common (and generally recommendedto use four spaces per indentation level one problem with the program in listing is that the output isn' very pretty to make it betteryou could right-align the columns and limit the precision of principal to two digits there are several ways to achieve this formatting the most widely used approach is to use the string formatting operator (%like thisprint "% % (yearprincipalprint("% % (yearprincipal)python now the output of the program looks like this format strings contain ordinary text and special formatting-character sequences such as "% ""% "and "%fthese sequences specify the formatting of particular type of data such as an integerstringor floating-point numberrespectively the specialcharacter sequences can also contain modifiers that specify width and precision for example"% dformats an integer right-aligned in column of width and "% fformats floating-point number so that only two digits appear after the decimal point the behavior of format strings is almost identical to the printf(function and is described in detail in "operators and expressions more modern approach to string formatting is to format each part individually using the format(function for exampleprint format(year," "),format(principal," "print(format(year," "),format(principal," ")python format(uses format specifiers that are similar to those used with the traditional string formatting operator (%for example" dformats an integer right-aligned in column of width and " fformats float-point number to have two digits of accuracy strings also have format(method that can be used to format many values at once for exampleprint "{ : { : }format(year,principalprint("{ : { : }format(year,principal)python in this examplethe number before the colon in "{ : }and "{ : }refers to the associated argument passed to the format(method and the part after the colon is the format specifier lib fl ff
17,856
conditionals the if and else statements can perform simple tests here' an exampleif bprint "computer says yeselseprint "computer says nothe bodies of the if and else clauses are denoted by indentation the else clause is optional to create an empty clauseuse the pass statementas followsif bpass do nothing elseprint "computer says noyou can form boolean expressions by using the orandand not keywordsif product ="gameand type ="pirate memoryand not (age )print " 'll take it!note writing complex test cases commonly results in statements that involve an annoyingly long line of code to improve readabilityyou can continue any statement to the next line by using backslash (\at the end of line as shown if you do thisthe normal indentation rules don' apply to the next lineso you are free to format the continued lines as you wish python does not have special switch or case statement for testing values to handle multiple-test casesuse the elif statementlike thisif suffix =htm"content "text/htmlelif suffix =jpg"content "image/jpegelif suffix =png"content "image/pngelseraise runtimeerror("unknown content type"to denote truth valuesuse the boolean values true and false here' an exampleif 'spamin shas_spam true elsehas_spam false all relational operators such as return true or false as results the in operator used in this example is commonly used to check whether value is contained inside of another object such as stringlistor dictionary it also returns true or falseso the preceding example could be shortened to thishas_spam 'spamin lib fl ff
17,857
tutorial introduction file input and output the following program opens file and reads its contents line by linef open("foo txt"line readline(while lineprint lineprint(line,end=''line readline( close(returns file object invokes readline(method on file trailing ',omits newline character use in python the open(function returns new file object by invoking methods on this objectyou can perform various file operations the readline(method reads single line of inputincluding the terminating newline the empty string is returned at the end of the file in the examplethe program is simply looping over all the lines in the file foo txt whenever program loops over collection of data like this (for instance input linesnumbersstringsetc )it is commonly known as iteration because iteration is such common operationpython provides dedicated statementforthat is used to iterate over items for instancethe same program can be written much more succinctly as followsfor line in open("foo txt")print lineto make the output of program go to fileyou can supply file to the print statement using >>as shown in the following examplef open("out"," "open file for writing while year <numyearsprincipal principal ( rateprint >> ,"% % (year,principalyear + close(the >syntax only works in python if you are using python change the print statement to the followingprint("% % (year,principal),file=fin additionfile objects support write(method that can be used to write raw data for examplethe print statement in the previous example could have been written this wayf write("% % \ (year,principal)although these examples have worked with filesthe same techniques apply to the standard output and input streams of the interpreter for exampleif you wanted to read user input interactivelyyou can read from the file sys stdin if you want to write data to the screenyou can write to sys stdoutwhich is the same file used to output data produced by the print statement for exampleimport sys sys stdout write("enter your name :"name sys stdin readline(in python this code can also be shortened to the followingname raw_input("enter your name :" lib fl ff
17,858
in python the raw_input(function is called input()but it works in exactly the same manner strings to create string literalsenclose them in singledoubleor triple quotes as followsa "hello worldb 'python is groovyc """computer says 'no'""the same type of quote used to start string must be used to terminate it triplequoted strings capture all the text that appears prior to the terminating triple quoteas opposed to singleand double-quoted stringswhich must be specified on one logical line triple-quoted strings are useful when the contents of string literal span multiple lines of text such as the followingprint '''content-typetext/html hello world click < href="''strings are stored as sequences of characters indexed by integersstarting at zero to extract single characteruse the indexing operator [ilike thisa "hello worldb [ 'oto extract substringuse the slicing operator [ :jthis extracts all characters from whose index is in the range < if either index is omittedthe beginning or end of the string is assumedrespectivelyc [: [ : [ : "hellod "worlde "lo wostrings are concatenated with the plus (+operatorg this is testpython never implicitly interprets the contents of string as numerical data ( as in other languages such as perl or phpfor examplealways concatenates stringsx " " " (string concatenationto perform mathematical calculationsstrings first have to be converted into numeric value using function such as int(or float(for examplez int(xint(yz (integer +non-string values can be converted into string representation by using the str()repr()or format(function here' an examples "the value of is str(xs "the value of is repr(xs "the value of is format( ," " lib fl ff
17,859
tutorial introduction although str(and repr(both create stringstheir output is usually slightly different str(produces the output that you get when you use the print statementwhereas repr(creates string that you type into program to exactly represent the value of an object for examplex str( ' repr( ' the inexact representation of in the previous example is not bug in python it is an artifact of double-precision floating-point numberswhich by their design can not exactly represent base- decimals on the underlying computer hardware the format(function is used to convert value to string with specific formatting applied for exampleformat( ," "' lists lists are sequences of arbitrary objects you create list by enclosing values in square bracketsas followsnames "dave""mark""ann""phillists are indexed by integersstarting with zero use the indexing operator to access and modify individual items of the lista names[ names[ "jeffreturns the third item of the list"annchanges the first item to "jeffto append new items to the end of listuse the append(methodnames append("paula"to insert an item into the middle of listuse the insert(methodnames insert( "thomas"you can extract or reassign portion of list by using the slicing operatorb names[ : returns "jeff""markc names[ :returns "thomas""ann""phil""paulanames[ 'jeffreplace the nd item in names with 'jeffnames[ : ['dave','mark','jeff'replace the first two items of the list with the list on the right use the plus (+operator to concatenate listsa [ , , [ , result is [ , , , , an empty list is created in one of two waysnames [names list(an empty list an empty list lib fl ff
17,860
lists can contain any kind of python objectincluding other listsas in the following examplea [ ,"dave", ["mark" [ , ]] items contained in nested lists are accessed by applying more than one indexing operationas followsa[ [ ][ [ ][ ][ returns "davereturns returns the program in listing illustrates few more advanced features of lists by reading list of numbers from file specified on the command line and outputting the minimum and maximum values listing advanced list features import sys load the sys module if len(sys argv! check number of command line arguments print "please supply filenameraise systemexit( open(sys argv[ ]filename on the command line lines readlines(read all lines into list close(convert all of the input values from strings to floats fvalues [float(linefor line in linesprint min and max values print "the minimum value is "min(fvaluesprint "the maximum value is "max(fvaluesthe first line of this program uses the import statement to load the sys module from the python library this module is being loaded in order to obtain command-line arguments the open(function uses filename that has been supplied as command-line option and placed in the list sys argv the readlines(method reads all the input lines into list of strings the expression [float(linefor line in linesconstructs new list by looping over all the strings in the list lines and applying the function float(to each element this particularly powerful method of constructing list is known as list comprehension because the lines in file can also be read using for loopthe program can be shortened by converting values using single statement like thisfvalues [float(linefor line in open(sys argv[ ])after the input lines have been converted into list of floating-point numbersthe built-in min(and max(functions compute the minimum and maximum values lib fl ff
17,861
tutorial introduction tuples to create simple data structuresyou can pack collection of values together into single object using tuple you create tuple by enclosing group of values in parentheses like thisstock ('goog' address ('www python org' person (first_namelast_namephonepython often recognizes that tuple is intended even if the parentheses are missingstock 'goog' address 'www python org', person first_namelast_namephone for completeness and -element tuples can be definedbut have special syntaxa ( (item, item -tuple (empty tuple -tuple (note the trailing comma -tuple (note the trailing commathe values in tuple can be extracted by numerical index just like list howeverit is more common to unpack tuples into set of variables like thisnamesharesprice stock hostport address first_namelast_namephone person although tuples support most of the same operations as lists (such as indexingslicingand concatenation)the contents of tuple cannot be modified after creation (that isyou cannot replacedeleteor append new elements to an existing tuplethis reflects the fact that tuple is best viewed as single object consisting of several partsnot as collection of distinct objects to which you might insert or remove items because there is so much overlap between tuples and listssome programmers are inclined to ignore tuples altogether and simply use lists because they seem to be more flexible although this worksit wastes memory if your program is going to create large number of small lists (that iseach containing fewer than dozen itemsthis is because lists slightly overallocate memory to optimize the performance of operations that add new items because tuples are immutablethey use more compact representation where there is no extra space tuples and lists are often used together to represent data for examplethis program shows how you might read file consisting of different columns of data separated by commasfile containing lines of the form "name,shares,pricefilename "portfolio csvportfolio [for line in open(filename)fields line split(","split each line into list name fields[ extract and convert individual fields shares int(fields[ ]price float(fields[ ]stock (name,shares,pricecreate tuple (namesharespriceportfolio append(stockappend to list of records the split(method of strings splits string into list of fields separated by the given delimiter character the resulting portfolio data structure created by this program lib fl ff
17,862
looks like two-dimension array of rows and columns each row is represented by tuple and can be accessed as followsportfolio[ ('goog' portfolio[ ('msft' individual items of data can be accessed like thisportfolio[ ][ portfolio[ ][ here' an easy way to loop over all of the records and expand fields into set of variablestotal for namesharesprice in portfoliototal +shares price sets set is used to contain an unordered collection of objects to create setuse the set(function and supply sequence of items such as followss set([ , , , ] set("hello"create set of numbers create set of unique characters unlike lists and tuplessets are unordered and cannot be indexed by numbers moreoverthe elements of set are never duplicated for exampleif you inspect the value of from the preceding codeyou get the followingt set([' '' '' '' ']notice that only one 'lappears sets support standard collection of operationsincluding unionintersectiondifferenceand symmetric difference here' an examplea union of and intersection of and set difference (items in tbut not in ssymmetric difference (items in or sbut not bothnew items can be added to set using add(or update() add(' ' update([ , , ]add single item adds multiple items to an item can be removed using remove() remove(' ' lib fl ff
17,863
tutorial introduction dictionaries dictionary is an associative array or hash table that contains objects indexed by keys you create dictionary by enclosing the values in curly braces (})like thisstock "name"goog""shares "price to access members of dictionaryuse the key-indexing operator as followsname stock["name"value stock["shares"shares["price"inserting or modifying objects works like thisstock["shares" stock["date""june although strings are the most common type of keyyou can use many other python objectsincluding numbers and tuples some objectsincluding lists and dictionariescannot be used as keys because their contents can change dictionary is useful way to define an object that consists of named fields as shown previously howeverdictionaries are also used as container for performing fast lookups on unordered data for examplehere' dictionary of stock pricesprices "goog "aapl "ibm "msft an empty dictionary is created in one of two waysprices {an empty dict prices dict(an empty dict dictionary membership is tested with the in operatoras in the following exampleif "scoxin pricesp prices["scox"elsep this particular sequence of steps can also be performed more compactly as followsp prices get("scox", to obtain list of dictionary keysconvert dictionary to listsyms list(pricessyms ["aapl""msft""ibm""goog"use the del statement to remove an element of dictionarydel prices["msft"dictionaries are probably the most finely tuned data type in the python interpreter soif you are merely trying to store and work with data in your programyou are almost always better off using dictionary than trying to come up with some kind of custom data structure on your own lib fl ff
17,864
iteration and looping the most widely used looping construct is the for statementwhich is used to iterate over collection of items iteration is one of python' richest features howeverthe most common form of iteration is to simply loop over all the members of sequence such as stringlistor tuple here' an examplefor in [ , , , , , , , , ]print " to the % power is % ( **nin this examplethe variable will be assigned successive items from the list [ , , , , on each iteration because looping over ranges of integers is quite commonthe following shortcut is often used for that purposefor in range( , )print " to the % power is % ( **nthe range( , [,stride]function creates an object that represents range of integers with values to - if the starting value is omittedit' taken to be zero an optional stride can also be given as third argument here' an examplea range( range( , range( , , range( , ,- , , , , , , , , , , , , , , , , , , , , one caution with range(is that in python the value it creates is fully populated list with all of the integer values for extremely large rangesthis can inadvertently consume all available memory thereforein older python codeyou will see programmers using an alternative function xrange(for examplefor in xrange( )statements , , , the object created by xrange(computes the values it represents on demand when lookups are requested for this reasonit is the preferred way to represent extremely large ranges of integer values in python the xrange(function has been renamed to range(and the functionality of the old range(function has been removed the for statement is not limited to sequences of integers and can be used to iterate over many kinds of objects including stringslistsdictionariesand files here' an examplea "hello worldprint out the individual characters in for in aprint ["dave","mark","ann","phil"print out the members of list for name in bprint name 'goog 'ibm 'aapl print out all of the members of dictionary for key in cprint keyc[keyprint all of the lines in file open("foo txt" lib fl ff
17,865
tutorial introduction for line in fprint linethe for loop is one of python' most powerful language features because you can create custom iterator objects and generator functions that supply it with sequences of values more details about iterators and generators can be found later in this and in "functions and functional programming functions you use the def statement to create functionas shown in the following exampledef remainder( , ) / * return /is truncating division to invoke functionsimply use the name of the function followed by its arguments enclosed in parenthesessuch as result remainder( , you can use tuple to return multiple values from functionas shown heredef divide( , ) / * return ( ,rif and are integersq is integer when returning multiple values in tupleyou can easily unpack the result into separate variables like thisquotientremainder divide( , to assign default value to function parameteruse assignmentdef connect(hostname,port,timeout= )function body when default values are given in function definitionthey can be omitted from subsequent function calls when omittedthe argument will simply take on the default value here' an exampleconnect('www python org' you also can invoke functions by using keyword arguments and supplying the arguments in arbitrary order howeverthis requires you to know the names of the arguments in the function definition here' an exampleconnect(port= ,hostname="www python org"when variables are created or assigned inside functiontheir scope is local that isthe variable is only defined inside the body of the function and is destroyed when the function returns to modify the value of global variable from inside functionuse the global statement as followscount def foo()global count count + changes the global variable count lib fl ff
17,866
generators instead of returning single valuea function can generate an entire sequence of results if it uses the yield statement for exampledef countdown( )print "counting down!while yield generate value (nn - any function that uses yield is known as generator calling generator function creates an object that produces sequence of results through successive calls to next(method (or _next_ (in python for examplec countdown( next(counting down next( next( the next(call makes generator function run until it reaches the next yield statement at this pointthe value passed to yield is returned by next()and the function suspends execution the function resumes execution on the statement following yield when next(is called again this process continues until the function returns normally you would not manually call next(as shown insteadyou hook it up to for loop like thisfor in countdown( )print icounting down generators are an extremely powerful way of writing programs based on processing pipelinesstreamsor data flow for examplethe following generator function mimics the behavior of the unix tail - command that' commonly used to monitor log filestail file (like tail -fimport time def tail( ) seek( , move to eof while trueline readline(try reading new line of text if not lineif nothingsleep briefly and try again time sleep( continue yield line here' generator that looks for specific substring in sequence of linesdef grep(linessearchtext)for line in linesif searchtext in lineyield line lib fl ff
17,867
tutorial introduction here' an example of hooking both of these generators together to create simple processing pipelinea python implementation of unix "tail - grep pythonwwwlog tail(open("access-log")pylines grep(wwwlog,"python"for line in pylinesprint linea subtle aspect of generators is that they are often mixed together with other iterable objects such as lists or files specificallywhen you write statement such as for item in ss could represent list of itemsthe lines of filethe result of generator functionor any number of other objects that support iteration the fact that you can just plug different objects in for can be powerful tool for creating extensible programs coroutines normallyfunctions operate on single set of input arguments howevera function can also be written to operate as task that processes sequence of inputs sent to it this type of function is known as coroutine and is created by using the yield statement as an expression (yieldas shown in this exampledef print_matches(matchtext)print "looking for"matchtext while trueline (yieldget line of text if matchtext in lineprint line to use this functionyou first call itadvance it to the first (yield)and then start sending data to it using send(for examplematcher print_matches("python"matcher next(advance to the first (yieldlooking for python matcher send("hello world"matcher send("python is cool"python is cool matcher send("yow!"matcher close(done with the matcher function call coroutine is suspended until value is sent to it using send(when this happensthat value is returned by the (yieldexpression inside the coroutine and is processed by the statements that follow processing continues until the next (yieldexpression is encountered--at which point the function suspends this continues until the coroutine function returns or close(is called on it as shown in the previous example coroutines are useful when writing concurrent programs based on producerconsumer problems where one part of program is producing data to be consumed by another part of the program in this modela coroutine represents consumer of data here is an example of using generators and coroutines togethera set of matcher coroutines matchers print_matches("python")print_matches("guido")print_matches("jython" lib fl ff
17,868
prep all of the matchers by calling next(for in matchersm next(feed an active log file into all matchers note for this to worka web server must be actively writing data to the log wwwlog tail(open("access-log")for line in wwwlogfor in matchersm send(linesend data into each matcher coroutine further details about coroutines can be found in objects and classes all values used in program are objects an object consists of internal data and methods that perform various kinds of operations involving that data you have already used objects and methods when working with the built-in types such as strings and lists for exampleitems [ items append( create list object call the append(method the dir(function lists the methods available on an object and is useful tool for interactive experimentation for exampleitems [ dir(items[' _add_ '' _class_ '' _contains_ '' _delattr_ '' _delitem_ ''append''count''extend''index''insert''pop''remove''reverse''sort'when inspecting objectsyou will see familiar methods such as append(and insert(listed howeveryou will also see special methods that always begin and end with double underscore these methods implement various language operations for examplethe _add_ (method implements the operatoritems _add_ ([ , ][ the class statement is used to define new types of objects and for object-oriented programming for examplethe following class defines simple stack with push()pop()and length(operationsclass stack(object)def _init_ (self)self stack def push(self,object)self stack append(objectdef pop(self)return self stack pop(def length(self)return len(self stackinitialize the stack in the first line of the class definitionthe statement class stack(objectdeclares stack to be an object the use of parentheses is how python specifies inheritance--in this casestack inherits from objectwhich is the root of all python types inside the class definitionmethods are defined using the def statement the first argument in each lib fl ff
17,869
tutorial introduction method always refers to the object itself by conventionself is the name used for this argument all operations involving the attributes of an object must explicitly refer to the self variable methods with leading and trailing double underscores are special methods for example_ _init_ is used to initialize an object after it' created to use classwrite code such as the followings stack( push("dave" push( push([ , , ] pop( pop(del create stack push some things onto it gets [ , , gets destroy in this examplean entirely new object was created to implement the stack howevera stack is almost identical to the built-in list object thereforean alternative approach would be to inherit from list and add an extra methodclass stack(list)add push(method for stack interface notelists already provide pop(method def push(self,object)self append(objectnormallyall of the methods defined within class apply only to instances of that class (that isthe objects that are createdhoweverdifferent kinds of methods can be defined such as static methods familiar to +and java programmers for exampleclass eventhandler(object)@staticmethod def dispatcherthread()while ( )wait for requests eventhandler dispatcherthread(call method like function in this case@staticmethod declares the method that follows to be static method @staticmethod is an example of using an decoratora topic that is discussed further in exceptions if an error occurs in your programan exception is raised and traceback message such as the following appearstraceback (most recent call last)file "foo py"line in ioerror[errno no such file or directory'file txtthe traceback message indicates the type of error that occurredalong with its location normallyerrors cause program to terminate howeveryou can catch and handle exceptions using try and except statementslike thistryf open("file txt"," "except ioerror as eprint lib fl ff
17,870
if an ioerror occursdetails concerning the cause of the error are placed in and control passes to the code in the except block if some other kind of exception is raisedit' passed to the enclosing code block (if anyif no errors occurthe code in the except block is ignored when an exception is handledprogram execution resumes with the statement that immediately follows the last except block the program does not return to the location where the exception occurred the raise statement is used to signal an exception when raising an exceptionyou can use one of the built-in exceptionslike thisraise runtimeerror("computer says no"or you can create your own exceptionsas described in the section "defining new exceptionsin program structure and control flow proper management of system resources such as locksfilesand network connections is often tricky problem when combined with exception handling to simplify such programmingyou can use the with statement with certain kinds of objects here is an example of writing code that uses mutex lockimport threading message_lock threading lock(with message_lockmessages add(newmessagein this examplethe message_lock object is automatically acquired when the with statement executes when execution leaves the context of the with blockthe lock is automatically released this management takes place regardless of what happens inside the with block for exampleif an exception occursthe lock is released when control leaves the context of the block the with statement is normally only compatible with objects related to system resources or the execution environment such as filesconnectionsand locks howeveruser-defined objects can define their own custom processing this is covered in more detail in the "context management protocolsection of "types and objects modules as your programs grow in sizeyou will want to break them into multiple files for easier maintenance to do thispython allows you to put definitions in file and use them as module that can be imported into other programs and scripts to create moduleput the relevant statements and definitions into file that has the same name as the module (note that the file must have py suffix here' an examplefile div py def divide( , ) / * return ( ,rif and are integersq is an integer to use your module in other programsyou can use the import statementimport div ab div divide( lib fl ff
17,871
tutorial introduction the import statement creates new namespace and executes all the statements in the associated py file within that namespace to access the contents of the namespace after importsimply use the name of the module as prefixas in div divide(in the preceding example if you want to import module using different namesupply the import statement with an optional as qualifieras followsimport div as foo , foo divide( , to import specific definitions into the current namespaceuse the from statementfrom div import divide , divide( , no longer need the div prefix to load all of module' contents into the current namespaceyou can also use the followingfrom div import as with objectsthe dir(function lists the contents of module and is useful tool for interactive experimentationimport string dir(string[' _builtins_ '' _doc_ '' _file_ '' _name_ ''_idmap''_idmapl''_lower''_swapcase''_upper''atof''atof_error''atoi''atoi_error''atol''atol_error''capitalize''capwords''center''count''digits''expandtabs''find'getting help when working with pythonyou have several sources of quickly available information firstwhen python is running in interactive modeyou can use the help(command to get information about built-in modules and other aspects of python simply type help(by itself for general information or help('modulename'for information about specific module the help(command can also be used to return information about specific functions if you supply function name most python functions have documentation strings that describe their usage to print the doc stringsimply print the _doc_ attribute here' an exampleprint issubclass _doc_ issubclass(cb-bool return whether class is subclass ( derived classof class when using tuple as the second argument issubclass( (ab))is shortcut for issubclass(xaor issubclass(xbor (etc lastbut not leastmost python installations also include the command pydocwhich can be used to return documentation about python modules simply type pydoc topic at system command prompt lib fl ff
17,872
lexical conventions and syntax his describes the syntactic and lexical conventions of python program topics include line structuregrouping of statementsreserved wordsliteralsoperatorstokensand source code encoding line structure and indentation each statement in program is terminated with newline long statements can span multiple lines by using the line-continuation character (\)as shown in the following examplea math cos( ( )math sin( ( )you don' need the line-continuation character when the definition of triple-quoted stringlisttupleor dictionary spans multiple lines more generallyany part of program enclosed in parentheses )brackets ]braces }or triple quotes can span multiple lines without use of the line-continuation character because they clearly denote the start and end of definition indentation is used to denote different blocks of codesuch as the bodies of functionsconditionalsloopsand classes the amount of indentation used for the first statement of block is arbitrarybut the indentation of the entire block must be consistent here' an exampleif astatement statement elsestatement statement consistent indentation inconsistent indentation (errorif the body of functionconditionalloopor class is short and contains only single statementit can be placed on the same linelike thisif aelsestatement statement to denote an empty body or blockuse the pass statement here' an exampleif apass elsestatements lib fl ff
17,873
lexical conventions and syntax although tabs can be used for indentationthis practice is discouraged the use of spaces is universally preferred (and encouragedby the python programming community when tab characters are encounteredthey're converted into the number of spaces required to move to the next column that' multiple of (for examplea tab appearing in column inserts enough spaces to move to column running python with the - option prints warning messages when tabs and spaces are mixed inconsistently within the same program block the -tt option turns these warning messages into taberror exceptions to place more than one statement on lineseparate the statements with semicolon (; line containing single statement can also be terminated by semicolonalthough this is unnecessary the character denotes comment that extends to the end of the line appearing inside quoted string doesn' start commenthowever finallythe interpreter ignores all blank lines except when running in interactive mode in this casea blank line signals the end of input when typing statement that spans multiple lines identifiers and reserved words an identifier is name used to identify variablesfunctionsclassesmodulesand other objects identifiers can include lettersnumbersand the underscore character (_but must always start with nonnumeric character letters are currently confined to the characters - and - in the iso-latin character set because identifiers are casesensitivefoo is different from foo special symbols such as $%and are not allowed in identifiers in additionwords such as ifelseand for are reserved and cannot be used as identifier names the following list shows all the reserved wordsand as assert break class continue def del elif else except exec finally for from global if import in is lambda nonlocal not or pass print raise return try while with yield identifiers starting or ending with underscores often have special meanings for exampleidentifiers starting with single underscore such as _foo are not imported by the from module import statement identifiers with leading and trailing double underscores such as _init_ are reserved for special methodsand identifiers with leading double underscores such as _bar are used to implement private class membersas described in "classes and object-oriented programming general-purpose use of similar identifiers should be avoided numeric literals there are four types of built-in numeric literalsn booleans integers lib fl ff
17,874
floating-point numbers complex numbers the identifiers true and false are interpreted as boolean values with the integer values of and respectively number such as is interpreted as decimal integer to specify an integer using octalhexadecimalor binary notationprecede the value with xor brespectively (for example fea or integers in python can have an arbitrary number of digitsso if you want to specify really large integerjust write out all of the digitsas in howeverwhen inspecting values and looking at old python codeyou might see large numbers written with trailing (lowercase lor characteras in this trailing is related to the fact that python internally represents integers as either fixed-precision machine integer or an arbitrary precision long integer type depending on the magnitude of the value in older versions of pythonyou could explicitly choose to use either type and would add the trailing to explicitly indicate the long type todaythis distinction is unnecessary and is actively discouraged soif you want large integer valuejust write it without the numbers such as and + are interpreted as floating-point numbers an integer or floating-point number with trailing or jsuch as jis an imaginary number you can create complex numbers with real and imaginary parts by adding real number and an imaginary numberas in string literals string literals are used to specify sequence of characters and are defined by enclosing text in single (')double (")or triple (''or """quotes there is no semantic difference between quoting styles other than the requirement that you use the same type of quote to start and terminate string singleand double-quoted strings must be defined on single linewhereas triple-quoted strings can span multiple lines and include all of the enclosed formatting (that isnewlinestabsspacesand so onadjacent strings (separated by white spacenewlineor line-continuation charactersuch as "hello'worldare concatenated to form single string "helloworldwithin string literalsthe backslash (\character is used to escape special characters such as newlinesthe backslash itselfquotesand nonprinting characters table shows the accepted escape codes unrecognized escape sequences are left in the string unmodified and include the leading backslash table standard character escape codes character description newline continuation backslash single quote double quote bell backspace escape null \\\\ \ \ \ lib fl ff
17,875
table continued character description \ \ \ line feed vertical tab horizontal tab carriage return form feed octal value (\ to \ unicode character (\ to \uffffunicode character (\ to \uffffffffunicode character name hexadecimal value (\ to \xff\ \ \ooo \uxxxx \uxxxxxxxx \ {charname\xhh the escape codes \ooo and \ are used to embed characters into string literal that can' be easily typed (that iscontrol codesnonprinting characterssymbolsinternational charactersand so onfor these escape codesyou have to specify an integer value corresponding to character value for exampleif you wanted to write string literal for the word "jalapeno"you might write it as "jalape\xf owhere \xf is the character code for in python string literals correspond to -bit character or byte-oriented data serious limitation of these strings is that they do not fully support international character sets and unicode to address this limitationpython uses separate string type for unicode data to write unicode string literalyou prefix the first quote with the letter "ufor examples "jalape\ oin python this prefix character is unnecessary (and is actually syntax erroras all strings are already unicode python will emulate this behavior if you run the interpreter with the - option (in which case all string literals will be treated as unicode and the prefix can be omittedregardless of which python version you are usingthe escape codes of \ \uand \ in table are used to insert arbitrary characters into unicode literal every unicode character has an assigned code pointwhich is typically denoted in unicode charts as +xxxx where xxxx is sequence of four or more hexadecimal digits (note that this notation is not python syntax but is often used by authors when describing unicode characters for examplethe character has code point of + the \ escape code is used to insert unicode characters with code points in the range + to +ffff (for example\ the \ escape code is used to insert characters in the range + and above (for example\ one subtle caution concerning the \ escape code is that unicode characters with code points above + usually get decomposed into pair of characters known as surrogate pair this has to do with the internal representation of unicode strings and is covered in more detail in "types and objects unicode characters also have descriptive name if you know the nameyou can use the \ {character nameescape sequence for examples "jalape\ {latin small letter with tilde}of lib fl ff
17,876
for an authoritative reference on code points and character namesconsult optionallyyou can precede string literal with an or rsuch as in '\dthese strings are known as raw strings because all their backslash characters are left intact--that isthe string literally contains the enclosed textincluding the backslashes the main use of raw strings is to specify literals where the backslash character has some significance examples might include the specification of regular expression patterns with the re module or specifying filename on windows machine (for exampler' :\newdata\tests'raw strings cannot end in single backslashsuch as "\within raw strings\uxxxx escape sequences are still interpreted as unicode charactersprovided that the number of preceding characters is odd for instanceur"\ defines raw unicode string with the single character + whereas ur"\\ defines seven-character string in which the first two characters are slashes and the remaining five characters are the literal " alsoin python the must appear after the in raw unicode strings as shown in python the prefix is unnecessary string literals should not be defined using sequence of raw bytes that correspond to data encoding such as utf- or utf- for exampledirectly writing raw utf- encoded string such as 'jalape\xc \xb osimply produces nine-character string + au+ + cu+ + + + + + fwhich is probably not what you intended this is because in utf- the multibyte sequence \xc \xb is supposed to represent the single character + not the two characters + and + to specify an encoded byte string as literalprefix the first quote with "bas in "jalape\xc \xb owhen definedthis literally creates string of single bytes from this representationit is possible to create normal string by decoding the value of the byte literal with its decode(method more details about this are covered in and "operators and expressions the use of byte literals is quite rare in most programs because this syntax did not appear until python and in that version there is no difference between byte literal and normal string in python howeverbyte literals are mapped to new bytes datatype that behaves differently than normal string (see appendix "python "containers values enclosed in square brackets ]parentheses )and braces denote collection of objects contained in listtupleand dictionaryrespectivelyas in the following examplea 'hellob ' ' ' ' list tuple dictionary listtupleand dictionary literals can span multiple lines without using the linecontinuation character (\in additiona trailing comma is allowed on the last item for examplea 'hello' lib fl ff
17,877
operatorsdelimitersand special symbols the following operators are recognized-*/*//<%/>**=&<!|>^+>><<the following tokens serve as delimiters for expressionslistsdictionariesand various parts of statementfor examplethe equal (=character serves as delimiter between the name and value of an assignmentwhereas the comma (,character is used to delimit arguments to functionelements in lists and tuplesand so on the period is also used in floatingpoint numbers and in the ellipsis used in extended slicing operations finallythe following special symbols are also usedthe characters and have no meaning in python and cannot appear in program except inside quoted string literal documentation strings if the first statement of moduleclassor function definition is stringthat string becomes documentation string for the associated objectas in the following exampledef fact( )"this function computes factorialif ( < )return elsereturn fact( code-browsing and documentation-generation tools sometimes use documentation strings the strings are accessible in the _doc_ attribute of an objectas shown hereprint fact _doc_ this function computes factorial the indentation of the documentation string must be consistent with all the other statements in definition in additiona documentation string cannot be computed or assigned from variable as an expression the documentation string always has to be string literal enclosed in quotes decorators functionmethodor class definitions may be preceded by special symbol known as decoratorthe purpose of which is to modify the behavior of the definition that follows decorators are denoted with the symbol and must be placed on separate line immediately before the corresponding functionmethodor class here' an exampleclass foo(object)@staticmethod def bar()pass lib fl ff
17,878
more than one decorator can be usedbut each one must be on separate line here' an example@foo @bar def spam()pass more information about decorators can be found in "functions and functional programming,and "classes and object-oriented programming source code encoding python source programs are normally written in standard -bit ascii howeverusers working in unicode environments may find this awkward--especially if they must write lot of string literals with international characters it is possible to write python source code in different encoding by including special encoding comment in the first or second line of python program#!/usr/bin/env python -*codingutf- -* "jalapenostring in quotes is directly encoded in utf- when the special codingcomment is suppliedstring literals may be typed in directly using unicode-aware editor howeverother elements of pythonincluding identifier names and reserved wordsshould still be restricted to ascii characters lib fl ff
17,879
lib fl ff
17,880
types and objects ll the data stored in python program is built around the concept of an object objects include fundamental data types such as numbersstringslistsand dictionaries howeverit' also possible to create user-defined objects in the form of classes in additionmost objects related to program structure and the internal operation of the interpreter are also exposed this describes the inner workings of the python object model and provides an overview of the built-in data types "operators and expressions,further describes operators and expressions "classes and object-oriented programming,describes how to create user-defined objects terminology every piece of data stored in program is an object each object has an identitya type (which is also known as its class)and value for examplewhen you write an integer object is created with the value of you can view the identity of an object as pointer to its location in memory is name that refers to this specific location the type of an objectalso known as the object' classdescribes the internal representation of the object as well as the methods and operations that it supports when an object of particular type is createdthat object is sometimes called an instance of that type after an instance is createdits identity and type cannot be changed if an object' value can be modifiedthe object is said to be mutable if the value cannot be modifiedthe object is said to be immutable an object that contains references to other objects is said to be container or collection most objects are characterized by number of data attributes and methods an attribute is value associated with an object method is function that performs some sort of operation on an object when the method is invoked as function attributes and methods are accessed using the dot operatoras shown in the following examplea real create complex number get the real part (an attributeb [ append( create list add new element using the append method object identity and type the built-in function id(returns the identity of an object as an integer this integer usually corresponds to the object' location in memoryalthough this is specific to the python implementation and no such interpretation of the identity should be made the lib fl ff
17,881
types and objects is operator compares the identity of two objects the built-in function type(returns the type of an object here' an example of different ways you might compare two objectscompare two objects def compare( , )if is ba and are the same object statements if =ba and have the same value statements if type(ais type( ) and have the same type statements the type of an object is itself an object known as the object' class this object is uniquely defined and is always the same for all instances of given type thereforethe type can be compared using the is operator all type objects are assigned names that can be used to perform type checking most of these names are built-inssuch as listdictand file here' an exampleif type(sis lists append(itemif type(dis dictd update(tbecause types can be specialized by defining classesa better way to check types is to use the built-in isinstance(objecttypefunction here' an exampleif isinstance( ,list) append(itemif isinstance( ,dict) update(tbecause the isinstance(function is aware of inheritanceit is the preferred way to check the type of any python object although type checks can be added to programtype checking is often not as useful as you might imagine for oneexcessive checking severely affects performance secondprograms don' always define objects that neatly fit into an inheritance hierarchy for instanceif the purpose of the preceding isinstance( ,liststatement is to test whether is "list-like,it wouldn' work with objects that had the same programming interface as list but didn' directly inherit from the built-in list type another option for adding type-checking to program is to define abstract base classes this is described in reference counting and garbage collection all objects are reference-counted an object' reference count is increased whenever it' assigned to new name or placed in container such as listtupleor dictionaryas shown herea [ append(bcreates an object with value increases reference count on increases reference count on lib fl ff
17,882
this example creates single object containing the value is merely name that refers to the newly created object when is assigned ab becomes new name for the same object and the object' reference count increases likewisewhen you place into listthe object' reference count increases again throughout the exampleonly one object contains all other operations are simply creating new references to the object an object' reference count is decreased by the del statement or whenever reference goes out of scope (or is reassignedhere' an exampledel decrease reference count of decrease reference count of [ decrease reference count of the current reference count of an object can be obtained using the sys getrefcount(function for examplea import sys sys getrefcount( in many casesthe reference count is much higher than you might guess for immutable data such as numbers and stringsthe interpreter aggressively shares objects between different parts of the program in order to conserve memory when an object' reference count reaches zeroit is garbage-collected howeverin some cases circular dependency may exist among collection of objects that are no longer in use here' an examplea [' ' [' ' del del contains reference to contains reference to in this examplethe del statements decrease the reference count of and and destroy the names used to refer to the underlying objects howeverbecause each object contains reference to the otherthe reference count doesn' drop to zero and the objects remain allocated (resulting in memory leakto address this problemthe interpreter periodically executes cycle detector that searches for cycles of inaccessible objects and deletes them the cycle-detection algorithm runs periodically as the interpreter allocates more and more memory during execution the exact behavior can be fine-tuned and controlled using functions in the gc module (see "python runtime services"references and copies when program makes an assignment such as ba new reference to is created for immutable objects such as numbers and stringsthis assignment effectively creates copy of howeverthe behavior is quite different for mutable objects such as lists and dictionaries here' an examplea [ , , , is true is reference to lib fl ff
17,883
types and objects [ - [ - change an element in notice how also changed because and refer to the same object in this examplea change made to one of the variables is reflected in the other to avoid thisyou have to create copy of an object rather than new reference two types of copy operations are applied to container objects such as lists and dictionariesa shallow copy and deep copy shallow copy creates new object but populates it with references to the items contained in the original object here' an examplea [ , list(ab is false append( [ [ ] [ [ ] [ ][ - [ [- ] [ [- ]create shallow copy of append element to notice that is unchanged modify an element inside notice the change inside in this casea and are separate list objectsbut the elements they contain are shared thereforea modification to one of the elements of also modifies an element of bas shown deep copy creates new object and recursively copies all the objects it contains there is no built-in operation to create deep copies of objects howeverthe copy deepcopy(function in the standard library can be usedas shown in the following exampleimport copy [ [ ] copy deepcopy(ab[ ][ - [ [- ] notice that is unchanged [ [ ]first-class objects all objects in python are said to be "first class "this means that all objects that can be named by an identifier have equal status it also means that all objects that can be named can be treated as data for examplehere is simple dictionary containing two valuesitems 'number 'text"hello worldf lib fl ff
17,884
the first-class nature of objects can be seen by adding some more unusual items to this dictionary here are some examplesitems["func"abs import math items["mod"math items["error"valueerror nums [ , , , items["append"nums append add the abs(function add module add an exception type add method of another object in this examplethe items dictionary contains functiona modulean exceptionand method of another object if you wantyou can use dictionary lookups on items in place of the original names and the code will still work for exampleitems["func"](- executes abs(- items["mod"sqrt( executes math sqrt( tryx int(" lot"except items["error"as esame as except valueerror as print("couldn' convert"couldn' convert items["append"]( executes nums append( nums [ the fact that everything in python is first-class is often not fully appreciated by new programmers howeverit can be used to write very compact and flexible code for examplesuppose you had line of text such as "goog, , and you wanted to convert it into list of fields with appropriate type-conversion here' clever way that you might do it by creating list of types (which are first-class objectsand executing few simple list processing operationsline "goog, , field_types [strintfloatraw_fields line split(','fields [ty(valfor ty,val in zip(field_types,raw_fields)fields ['goog' built-in types for representing data there are approximately dozen built-in data types that are used to represent most of the data used in programs these are grouped into few major categories as shown in table the type name column in the table lists the name or expression that you can use to check for that type using isinstance(and other type-related functions certain types are only available in python and have been indicated as such (in python they have been deprecated or merged into one of the other typesf lib fl ff
17,885
table built-in types for data representation type category type name description none numbers type(noneint long the null object none integer arbitrary-precision integer (python onlyfloating point complex number boolean (true or falsecharacter string unicode character string (python onlylist tuple range of integers created by xrange((in python it is called range dictionary mutable set immutable set sequences mapping sets float complex bool str unicode list tuple xrange dict set frozenset the none type the none type denotes null object (an object with no valuepython provides exactly one null objectwhich is written as none in program this object is returned by functions that don' explicitly return value none is frequently used as the default value of optional argumentsso that the function can detect whether the caller has actually passed value for that argument none has no attributes and evaluates to false in boolean expressions numeric types python uses five numeric typesbooleansintegerslong integersfloating-point numbersand complex numbers except for booleansall numeric objects are signed all numeric types are immutable booleans are represented by two valuestrue and false the names true and false are respectively mapped to the numerical values of and integers represent whole numbers in the range of - to (the range may be larger on some machineslong integers represent whole numbers of unlimited range (limited only by available memoryalthough there are two integer typespython tries to make the distinction seamless (in factin python the two types have been unified into single integer typethusalthough you will sometimes see references to long integers in existing python codethis is mostly an implementation detail that can be ignored--just use the integer type for all integer operations the one exception is in code that performs explicit type checking for integer values in python the expression isinstance(xintwill return false if is an integer that has been promoted to long floating-point numbers are represented using the native double-precision ( -bitrepresentation of floating-point numbers on the machine normally this is ieee which provides approximately digits of precision and an exponent in the range of lib fl ff
17,886
- to this is the same as the double type in python doesn' support -bit single-precision floating-point numbers if precise control over the space and precision of numbers is an issue in your programconsider using the numpy extension (which can be found at complex numbers are represented as pair of floating-point numbers the real and imaginary parts of complex number are available in real and imag the method conjugate(calculates the complex conjugate of (the conjugate of +bj is -bjnumeric types have number of properties and methods that are meant to simplify operations involving mixed arithmetic for simplified compatibility with rational numbers (found in the fractions module)integers have the properties numerator and denominator an integer or floating-point number has the properties real and imag as well as the method conjugate(for compatibility with complex numbers floating-point number can be converted into pair of integers representing fraction using as_integer_ratio(the method is_integer(tests if floating-point number represents an integer value methods hex(and fromhex(can be used to work with floating-point numbers using their low-level binary representation several additional numeric types are defined in library modules the decimal module provides support for generalized base- decimal arithmetic the fractions module adds rational number type these modules are covered in "mathematics sequence types sequences represent ordered sets of objects indexed by non-negative integers and include stringslistsand tuples strings are sequences of charactersand lists and tuples are sequences of arbitrary python objects strings and tuples are immutablelists allow insertiondeletionand substitution of elements all sequences support iteration operations common to all sequences table shows the operators and methods that you can apply to all sequence types element of sequence is selected using the indexing operator [ ]and subsequences are selected using the slicing operator [ :jor extended slicing operator [ : :stride(these operations are described in the length of any sequence is returned using the built-in len(sfunction you can find the minimum and maximum values of sequence by using the built-in min(sand max(sfunctions howeverthese functions only work for sequences in which the elements can be ordered (typically numbers and stringssum(ssums items in but only works for numeric data table shows the additional operators that can be applied to mutable sequences such as lists table operations and methods applicable to all sequences item description [is[ :jreturns element of sequence returns slice returns an extended slice [ : :stridef lib fl ff
17,887
table continued item description len(smin(smax(snumber of elements in minimum value in maximum value in sum of items in checks whether all items in are true checks whether any item in is true sum( [,initial]all(sany(stable operations applicable to mutable sequences item description [iv [ :jt [ : :stridet del [idel [ :jdel [ : :strideitem assignment slice assignment extended slice assignment item deletion slice deletion extended slice deletion lists lists support the methods shown in table the built-in function list(sconverts any iterable type to list if is already listthis function constructs new list that' shallow copy of the append(xmethod appends new elementxto the end of the list the index(xmethod searches the list for the first occurrence of if no such element is founda valueerror exception is raised similarlythe remove(xmethod removes the first occurrence of from the list or raises valueerror if no such item exists the extend(tmethod extends the list by appending the elements in sequence the sort(method sorts the elements of list and optionally accepts key function and reverse flagboth of which must be specified as keyword arguments the key function is function that is applied to each element prior to comparison during sorting if giventhis function should take single item as input and return the value that will be used to perform the comparison while sorting specifying key function is useful if you want to perform special kinds of sorting operations such as sorting list of stringsbut with case insensitivity the reverse(method reverses the order of the items in the list both the sort(and reverse(methods operate on the list elements in place and return none table list methods method description list(ss append(xs extend(ts count(xconverts to list appends new elementxto the end of appends new listtto the end of counts occurrences of in lib fl ff
17,888
table method continued description index( [,start [,stop]]returns the smallest where [ ]== start and stop optionally specify the starting and ending index for the search insert( ,xinserts at index pop([ ]returns the element and removes it from the list if is omittedthe last element is returned remove(xsearches for and removes it from reverse(reverses items of in place sort([key [reverse]]sorts items of in place key is key function reverse is flag that sorts the list in reverse order key and reverse should always be specified as keyword arguments strings python provides two string object types byte strings are sequences of bytes containing -bit data they may contain binary data and embedded null bytes unicode strings are sequences of unencoded unicode characterswhich are internally represented by -bit integers this allows for , unique character values although the unicode standard supports up to million unique character valuesthese extra characters are not supported by python by default insteadthey are encoded as special twocharacter ( -bytesequence known as surrogate pair--the interpretation of which is up to the application as an optional featurepython may be built to store unicode characters using -bit integers when enabledthis allows python to represent the entire range of unicode values from + to + all unicode-related functions are adjusted accordingly strings support the methods shown in table although these methods operate on string instancesnone of these methods actually modifies the underlying string data thusmethods such as capitalize() center()and expandtabs(always return new string as opposed to modifying the string character tests such as isalnum(and isupper(return true or false if all the characters in the string satisfy the test furthermorethese tests always return false if the length of the string is zero the find() index() rfind()and rindex(methods are used to search for substring all these functions return an integer index to the substring in in additionthe find(method returns - if the substring isn' foundwhereas the index(method raises valueerror exception the replace(method is used to replace substring with replacement text it is important to emphasize that all of these methods only work with simple substrings regular expression pattern matching and searching is handled by functions in the re library module the split(and rsplit(methods split string into list of fields separated by delimiter the partition(and rpartition(methods search for separator substring and partition into three parts corresponding to text before the separatorthe separator itselfand text after the separator many of the string methods accept optional start and end parameterswhich are integer values specifying the starting and ending indices in in most casesthese values lib fl ff
17,889
may be given negative valuesin which case the index is taken from the end of the string the translate(method is used to perform advanced character substitutions such as quickly stripping all control characters out of string as an argumentit accepts translation table containing one-to-one mapping of characters in the original string to characters in the result for -bit stringsthe translation table is -character string for unicodethe translation table can be any sequence object where [nreturns an integer character code or unicode character corresponding to the unicode character with integer value the encode(and decode(methods are used to transform string data to and from specified character encoding as inputthese accept an encoding name such as 'ascii''utf- 'or 'utf- these methods are most commonly used to convert unicode strings into data encoding suitable for / operations and are described further in "input and output be aware that in python the encode(method is only available on stringsand the decode(method is only available on the bytes datatype the format(method is used to perform string formatting as argumentsit accepts any combination of positional and keyword arguments placeholders in denoted by {itemare replaced by the appropriate argument positional arguments can be referenced using placeholders such as { and { keyword arguments are referenced using placeholder with name such as {namehere is an examplea "your name is { and your age is {age} format("mike"age= 'your name is mike and your age is within the special format stringsthe {itemplaceholders can also include simple index and attribute lookup placeholder of {item[ ]where is number performs sequence lookup on item placeholder of {item[key]where key is nonnumeric string performs dictionary lookup of item["key" placeholder of {item attrrefers to attribute attr of item further details on the format(method can be found in the "string formattingsection of table string methods method description capitalize( center(width [pad]capitalizes the first character centers the string in field of length width pad is padding character counts occurrences of the specified substring sub decodes string and returns unicode string (byte strings onlyreturns an encoded version of the string (unicode strings onlychecks the end of the string for suffix replaces tabs with spaces finds the first occurrence of the specified substring sub or returns - count(sub [,start [,end]] decode([encoding [,errors]] encode([encoding [,errors]] endswith(suffix [,start [,end]] expandtabs([tabsize] find(sub [start [,end]] lib fl ff
17,890
table continued method description format(*args**kwargss index(sub [start [,end]]formats finds the first occurrence of the specified substring sub or raises an error checks whether all characters are alphanumeric checks whether all characters are alphabetic checks whether all characters are digits checks whether all characters are lowercase checks whether all characters are whitespace checks whether the string is titlecased string (first letter of each word capitalizedchecks whether all characters are uppercase joins the strings in sequence with as separator left-aligns in string of size width converts to lowercase removes leading whitespace or characters supplied in chrs partitions string based on separator string sep returns tuple (head,sep,tailor ( "",""if sep isn' found replaces substring finds the last occurrence of substring finds the last occurrence or raises an error right-aligns in string of length width partitions based on separator sepbut searches from the end of the string splits string from the end of the string using sep as delimiter maxsplit is the maximum number of splits to perform if maxsplit is omittedthe result is identical to the split(method removes trailing whitespace or characters supplied in chrs splits string using sep as delimiter maxsplit is the maximum number of splits to perform isalnum( isalpha( isdigit( islower( isspace( istitle( isupper( join(ts ljust(width [fill] lower( lstrip([chrs] partition(seps replace(oldnew [,maxreplace] rfind(sub [,start [,end]] rindex(sub [,start [,end]] rjust(width [fill] rpartition(seps rsplit([sep [,maxsplit]] rstrip([chrs] split([sep [,maxsplit]] lib fl ff
17,891
table continued splits string into list of lines if keepends is trailing newlines are preserved startswith(prefix [,start [,end]]checks whether string starts with prefix strip([chrs]removes leading and trailing whitespace or characters supplied in chrs swapcase(converts uppercase to lowercaseand vice versa title(returns title-cased version of the string translate(table [,deletechars]translates string using character translation table tableremoving characters in deletechars upper(converts string to uppercase zfill(widthpads string with zeros on the left up to the specified width splitlines([keepends]xrange(objects the built-in function xrange([ ,] [,stride]creates an object that represents range of integers such that < the first indexiand the stride are optional and have default values of and respectively an xrange object calculates its values whenever it' accessed and although an xrange object looks like sequenceit is actually somewhat limited for examplenone of the standard slicing operations are supported this limits the utility of xrange to only few applications such as iterating in simple loops it should be noted that in python xrange(has been renamed to range(howeverit operates in exactly the same manner as described here mapping types mapping object represents an arbitrary collection of objects that are indexed by another collection of nearly arbitrary key values unlike sequencea mapping object is unordered and can be indexed by numbersstringsand other objects mappings are mutable dictionaries are the only built-in mapping type and are python' version of hash table or associative array you can use any immutable object as dictionary key value (stringsnumberstuplesand so onlistsdictionariesand tuples containing mutable objects cannot be used as keys (the dictionary type requires key values to remain constantto select an item in mapping objectuse the key index operator [ ]where is key value if the key is not founda keyerror exception is raised the len(mfunction returns the number of items contained in mapping object table lists the methods and operations lib fl ff
17,892
table item methods and operations for dictionaries description returns the number of items in returns the item of with key sets [kto del [kremoves [kfrom in returns true if is key in clear(removes all items from copy(makes copy of fromkeys( [,value]create new dictionary with keys from sequence and values all set to value get( [, ]returns [kif foundotherwisereturns has_key(kreturns true if has key kotherwisereturns false (deprecateduse the in operator instead python onlym items(returns sequence of (key,valuepairs keys(returns sequence of key values pop( [,default]returns [kif found and removes it from motherwisereturns default if supplied or raises keyerror if not popitem(removes random (key,valuepair from and returns it as tuple setdefault( [ ]returns [kif foundotherwisereturns and sets [kv update(badds all objects from to values(returns sequence of all values in len(mm[km[ ]= most of the methods in table are used to manipulate or retrieve the contents of dictionary the clear(method removes all items the update(bmethod updates the current mapping object by inserting all the (key,valuepairs found in the mapping object the get( [, ]method retrieves an object but allows for an optional default valuevthat' returned if no such key exists the setdefault( [, ]method is similar to get()except that in addition to returning if no object existsit sets [kv if is omittedit defaults to none the pop(method returns an item from dictionary and removes it at the same time the popitem(method is used to iteratively destroy the contents of dictionary the copy(method makes shallow copy of the items contained in mapping object and places them in new mapping object the fromkeys( [,value]method creates new mapping with keys all taken from sequence the type of the resulting mapping will be the same as the value associated with all of these keys is set to none unless an alternative value is given with the optional value parameter the fromkeys(method is defined as class methodso an alternative way to invoke it would be to use the class name such as dict fromkeys(the items(method returns sequence containing (key,valuepairs the keys(method returns sequence with all the key valuesand the values(method returns sequence with all the values for these methodsyou should assume that the only safe operation that can be performed on the result is iteration in python the result is listbut in python the result is an iterator that iterates over the current contents of the mapping if you write code that simply assumes it is an iteratorit will lib fl ff
17,893
be generally compatible with both versions of python if you need to store the result of these methods as datamake copy by storing it in list for exampleitems list( items()if you simply want list of all keysuse keys list(mset types set is an unordered collection of unique items unlike sequencessets provide no indexing or slicing operations they are also unlike dictionaries in that there are no key values associated with the objects the items placed into set must be immutable two different set types are availableset is mutable setand frozenset is an immutable set both kinds of sets are created using pair of built-in functionss set([ , , , ] frozenset([' ', ,'hello']both set(and frozenset(populate the set by iterating over the supplied argument both kinds of sets provide the methods outlined in table table methods and operations for set types item description returns the number of items in makes copy of set difference returns all the items in sbut not in intersection returns all the items that are both in and in isdisjoint(treturns true if and have no items in common issubset(treturns true if is subset of issuperset(treturns true if is superset of symmetric_difference(tsymmetric difference returns all the items that are in or tbut not in both sets union(tunion returns all items in or len(ss copy( difference(ts intersection(tthe difference( ) intersection( ) symmetric_difference( )and union(tmethods provide the standard mathematical operations on sets the returned value has the same type as (set or frozensetthe parameter can be any python object that supports iteration this includes setsliststuplesand strings these set operations are also available as mathematical operatorsas described further in mutable sets (setadditionally provide the methods outlined in table table methods for mutable set types item description add(itemadds item to has no effect if item is already in removes all items from removes all the items from that are also in clear( difference_update(tf lib fl ff
17,894
table continued item description removes item from if item is not member of snothing happens intersection_update(tcomputes the intersection of and and leaves the result in pop(returns an arbitrary set element and removes it from remove(itemremoves item from if item is not memberkeyerror is raised symmetric_difference_update(tcomputes the symmetric difference of and and leaves the result in update(tadds all the items in to may be another seta sequenceor any object that supports iteration discard(itemall these operations modify the set in place the parameter can be any object that supports iteration built-in types for representing program structure in pythonfunctionsclassesand modules are all objects that can be manipulated as data table shows types that are used to represent various elements of program itself table built-in python types for program structure type category type name description callable types builtinfunctiontype type object types functiontype types methodtype types moduletype object type built-in function or method type of built-in types and classes ancestor of all types and classes user-defined function class method module ancestor of all types and classes type of built-in types and classes modules classes types note that object and type appear twice in table because classes and types are both callable as function callable types callable types represent objects that support the function call operation there are several flavors of objects with this propertyincluding user-defined functionsbuilt-in functionsinstance methodsand classes lib fl ff
17,895
types and objects user-defined functions user-defined functions are callable objects created at the module level by using the def statement or with the lambda operator here' an exampledef foo( , )return bar lambda ,yx user-defined function has the following attributesattribute(sdescription _doc_ _name_ _dict_ _code_ _defaults_ _globals_ _closure_ documentation string function name dictionary containing function attributes byte-compiled code tuple containing the default arguments dictionary defining the global namespace tuple containing data related to nested scopes in older versions of python many of the preceding attributes had names such as func_codefunc_defaultsand so on the attribute names listed are compatible with python and python methods methods are functions that are defined inside class definition there are three common types of methods--instance methodsclass methodsand static methodsclass foo(object)def instance_method(self,arg)statements @classmethod def class_method(cls,arg)statements @staticmethod def static_method(arg)statements an instance method is method that operates on an instance belonging to given class the instance is passed to the method as the first argumentwhich is called self by convention class method operates on the class itself as an object the class object is passed to class method in the first argumentcls static method is just function that happens to be packaged inside class it does not receive an instance or class object as first argument both instance and class methods are represented by special object of type types methodtype howeverunderstanding this special type requires careful understanding of how object attribute lookup works the process of looking something up on an object is always separate operation from that of making function call when you invoke methodboth operations occurbut as distinct steps this example illustrates the process of invoking instance_method(argon an instance of foo in the preceding listingf foo(meth instance_method meth( create an instance lookup the method and notice the lack of (now call the method lib fl ff
17,896
in this examplemeth is known as bound method bound method is callable object that wraps both function (the methodand an associated instance when you call bound methodthe instance is passed to the method as the first parameter (selfthusmeth in the example can be viewed as method call that is primed and ready to go but which has not been invoked using the function call operator (method lookup can also occur on the class itself for exampleumeth foo instance_method umeth( , lookup instance_method on foo call itbut explicitly supply self in this exampleumeth is known as an unbound method an unbound method is callable object that wraps the method functionbut which expects an instance of the proper type to be passed as the first argument in the examplewe have passed fa an instance of fooas the first argument if you pass the wrong kind of objectyou get typeerror for exampleumeth("hello", traceback (most recent call last)file ""line in typeerrordescriptor 'instance_methodrequires 'fooobject but received 'strfor user-defined classesbound and unbound methods are both represented as an object of type types methodtypewhich is nothing more than thin wrapper around an ordinary function object the following attributes are defined for method objectsattribute description _doc_ _name_ _class_ _func_ _self_ documentation string method name class in which this method was defined function object implementing the method instance associated with the method (none if unboundone subtle feature of python is that unbound methods are no longer wrapped by types methodtype object if you access foo instance_method as shown in earlier examplesyou simply obtain the raw function object that implements the method moreoveryou'll find that there is no longer any type checking on the self parameter built-in functions and methods the object types builtinfunctiontype is used to represent functions and methods implemented in and +the following attributes are available for built-in methodsattribute description _doc_ _name_ _self_ documentation string function/method name instance associated with the method (if boundfor built-in functions such as len() _self_ is set to noneindicating that the function isn' bound to any specific object for built-in methods such as appendwhere is list object_ _self_ is set to lib fl ff
17,897
types and objects classes and instances as callables class objects and instances also operate as callable objects class object is created by the class statement and is called as function in order to create new instances in this casethe arguments to the function are passed to the _init_ (method of the class in order to initialize the newly created instance an instance can emulate function if it defines special method_ _call_ (if this method is defined for an instancexthen (argsinvokes the method _call_ (argsclassestypesand instances when you define classthe class definition normally produces an object of type type here' an exampleclass foo(object)pass type(foothe following table shows commonly used attributes of type object tattribute description _doc_ _name_ _bases_ _dict_ _module_ _abstractmethods_ documentation string class name tuple of base classes dictionary holding class methods and variables module name in which the class is defined set of abstract method names (may be undefined if there aren' anywhen an object instance is createdthe type of the instance is the class that defined it here' an examplef foo(type(fthe following table shows special attributes of an instance iattribute description _class_ _dict_ class to which the instance belongs dictionary holding instance data the _dict_ attribute is normally where all of the data associated with an instance is stored when you make assignments such as attr valuethe value is stored here howeverif user-defined class uses _slots_ _a more efficient internal representation is used and instances will not have _dict_ attribute more details on objects and the organization of the python object system can be found in modules the module type is container that holds objects loaded with the import statement when the statement import foo appears in programfor examplethe name foo is lib fl ff
17,898
assigned to the corresponding module object modules define namespace that' implemented using dictionary accessible in the attribute _dict_ whenever an attribute of module is referenced (using the dot operator)it' translated into dictionary lookup for examplem is equivalent to _dict_ [" "likewiseassignment to an attribute such as is equivalent to _dict_ [" " the following attributes are availableattribute description _dict_ _doc_ _name_ _file_ _path_ dictionary associated with the module module documentation string name of the module file from which the module was loaded fully qualified package nameonly defined when the module object refers to package built-in types for interpreter internals number of objects used by the internals of the interpreter are exposed to the user these include traceback objectscode objectsframe objectsgenerator objectsslice objectsand the ellipsis as shown in table it is relatively rare for programs to manipulate these objects directlybut they may be of practical use to tool-builders and framework designers table built-in python types for interpreter internals type name description types codetype types frametype types generatortype types tracebacktype slice ellipsis byte-compiled code execution frame generator object stack traceback of an exception generated by extended slices used in extended slices code objects code objects represent raw byte-compiled executable codeor bytecodeand are typically returned by the built-in compile(function code objects are similar to functions except that they don' contain any context related to the namespace in which the code was definednor do code objects store information about default argument values code objectchas the following read-only attributesattribute description co_name co_argcount co_nlocals co_varnames function name number of positional arguments (including default valuesnumber of local variables used by the function tuple containing names of local variables lib fl ff
17,899
types and objects attribute description tuple containing names of variables referenced by nested functions co_freevars tuple containing names of free variables used by nested functions co_code string representing raw bytecode co_consts tuple containing the literals used by the bytecode co_names tuple containing names used by the bytecode co_filename name of the file in which the code was compiled co_firstlineno first line number of the function co_lnotab string encoding bytecode offsets to line numbers co_stacksize required stack size (including local variablesc co_flags integer containing interpreter flags bit is set if the function uses variable number of positional arguments using "*argsbit is set if the function allows arbitrary keyword arguments using "**kwargsall other bits are reserved co_cellvars frame objects frame objects are used to represent execution frames and most frequently occur in traceback objects (described nexta frame objectfhas the following read-only attributesattribute description f_back f_code f_locals f_globals f_builtins f_lineno f_lasti previous stack frame (toward the callercode object being executed dictionary used for local variables dictionary used for global variables dictionary used for built-in names line number current instruction this is an index into the bytecode string of f_code the following attributes can be modified (and are used by debuggers and other tools)attribute description f_trace f_exc_type f_exc_value f_exc_traceback function called at the start of each source code line most recent exception type (python onlymost recent exception value (python onlymost recent exception traceback (python onlytraceback objects traceback objects are created when an exception occurs and contain stack trace information when an exception handler is enteredthe stack trace can be retrieved using the lib fl ff