Answer
stringlengths
0
5.21k
Question
stringlengths
4
109
Its probably best to cite your favorite book about PythonThevery first articleabout Python was written in 1991 and is now quite outdatedGuido van Rossum and Jelke de Boer Interactively Testing Remote Servers Using the Python Programming Language CWI Quarterly Volume 4 Issue 4 December 1991 Amsterdam pp 283303
Are there any published articles about python that i can reference?
here are numerous tutorials and books available The standard documentation includesThe Python TutorialConsultthe Beginners Guideto find information for beginning Python programmers including lists of tutorials
I ve never programmed before is there a python tutorial?
Alpha and beta releases are available fromhttpswwwpythonorgdownloads All releases are announced on the complangpython and complangpythonannounce newsgroups and on the Python home page athttpswwwpythonorg an RSS feed of news is availableYou can also access the development version of Python through Git SeeThe Python Developers Guidefor details
How do i get a beta test version of python?
In general no There are already millions of lines of Python code around the world so any change in the language that invalidates more than a very small fraction of existing programs has to be frowned upon Even if you can provide a conversion program theres still the problem of updating all documentation many books have been written about Python and we dont want to invalidate them all at a single strokeProviding a gradual upgrade path is necessary if a feature has to be changedPEP 5describes the procedure followed for introducing backwardincompatible changes while minimizing disruption for users
Is it reasonable to propose incompatible changes to python?
Seehttpspepspythonorgfor the Python Enhancement Proposals PEPs PEPs are design documents describing a suggested new feature for Python providing a concise technical specification and a rationale Look for a PEP titled Python XY Release Schedule where XY is a version that hasnt been publicly released yetNew development is discussed onthe pythondev mailing list
What new developments are expected for python in the future?
e Python projects infrastructure is located all over the world and is managed by the Python Infrastructure Team Detailshere
Where in the world is www python org located?
Python is an interpreted interactive objectoriented programming language It incorporates modules exceptions dynamic typing very high level dynamic data types and classes It supports multiple programming paradigms beyond objectoriented programming such as procedural and functional programming Python combines remarkable power with very clear syntax It has interfaces to many system calls and libraries as well as to various window systems and is extensible in C or C It is also usable as an extension language for applications that need a programmable interface Finally Python is portable it runs on many Unix variants including Linux and macOS and on WindowsTo find out more start withThe Python Tutorial TheBeginners Guide to Pythonlinks to other introductory tutorials and resources for learning Python
What is python?
Very stable New stable releases have been coming out roughly every 6 to 18 months since 1991 and this seems likely to continue As of version 39 Python will have a new feature release every 12 months PEP 602The developers issue bugfix releases of older versions so the stability of existing releases gradually improves Bugfix releases indicated by a third component of the version number eg 353 362 are managed for stability only fixes for known problems are included in a bugfix release and its guaranteed that interfaces will remain the same throughout a series of bugfix releasesThe latest stable releases can always be found on thePython download page There are two productionready versions of Python 2x and 3x The recommended version is 3x which is supported by most widely used libraries Although 2x is still widely usedit is not maintained anymore
How stable is python?
The latest Python source distribution is always available from pythonorg athttpswwwpythonorgdownloads The latest development sources can be obtained athttpsgithubcompythoncpythonThe source distribution is a gzipped tar file containing the complete C source Sphinxformatted documentation Python library modules example programs and several useful pieces of freely distributable software The source will compile and run out of the box on most UNIX platformsConsult theGetting Started section of the Python Developers Guidefor more information on getting the source code and compiling it
How do i obtain a copy of the python source?
Python is a highlevel generalpurpose programming language that can be applied to many different classes of problemsThe language comes with a large standard library that covers areas such as string processing regular expressions Unicode calculating differences between files internet protocols HTTP FTP SMTP XMLRPC POP IMAP software engineering unit testing logging profiling parsing Python code and operating system interfaces system calls filesystems TCPIP sockets Look at the table of contents forThe Python Standard Libraryto get an idea of whats available A wide variety of thirdparty extensions are also available Consultthe Python Package Indexto find packages of interest to you
What is python good for?
o but it helps
Do i have to like monty python s flying circus?
Yes there are many and more are being published See the pythonorg wiki athttpswikipythonorgmoinPythonBooksfor a listYou can also search online bookstores for Python and filter out the Monty Python references or perhaps search for Python and language
Are there any books on python?
Seehttpswwwpythonorgaboutsuccessfor a list of projects that use Python Consulting the proceedings forpast Python conferenceswill reveal contributions from many different companies and organizationsHighprofile Python projects includethe Mailman mailing list managerandthe Zope application server Several Linux distributions most notablyRed Hat have written part or all of their installer and system administration software in Python Companies that use Python internally include Google Yahoo and Lucasfilm Ltd
Have any significant projects been done in python?
You can do anything you want with the source as long as you leave the copyrights in and display those copyrights in any documentation about Python that you produce If you honor the copyright rules its OK to use Python for commercial use to sell copies of Python in source or binary form modified or unmodified or to sell products that incorporate Python in some form We would still like to know about all commercial use of Python of courseSeethe license pageto find further explanations and the full text of the PSF LicenseThe Python logo is trademarked and in certain cases permission is required to use it Consultthe Trademark Usage Policyfor more information
Are there copyright restrictions on the use of python?
YesIt is still common to start students with a procedural and statically typed language such as Pascal C or a subset of C or Java Students may be better served by learning Python as their first language Python has a very simple and consistent syntax and a large standard library and most importantly using Python in a beginning programming course lets students concentrate on important programming skills such as problem decomposition and data type design With Python students can be quickly introduced to basic concepts such as loops and procedures They can probably even work with userdefined objects in their very first courseFor a student who has never programmed before using a statically typed language seems unnatural It presents additional complexity that the student must master and slows the pace of the course The students are trying to learn to think like a computer decompose problems design consistent interfaces and encapsulate data While learning to use a statically typed language is important in the long term it is not necessarily the best topic to address in the students first programming courseMany other aspects of Python make it a good first language Like Java Python has a large standard library so that students can be assigned programming projects very early in the course thatdosomething Assignments arent restricted to the standard fourfunction calculator and check balancing programs By using the standard library students can gain the satisfaction of working on realistic applications as they learn the fundamentals of programming Using the standard library also teaches students about code reuse Thirdparty modules such as PyGame are also helpful in extending the students reachPythons interactive interpreter enables students to test language features while theyre programming They can keep a window with the interpreter running while they enter their programs source in another window If they cant remember the methods for a list they can do something like thisLdirLadd class contains delattr delitemdir doc eq format gegetattribute getitem gt hash iaddimul init iter le len ltmul ne new reduce reduceexrepr reversed rmul setattr setitemsizeof str subclasshook append clearcopy count extend index insert pop removereverse sortdfordindirLifnotindappend clear copy count extend index insert pop remove reverse sorthelpLappendHelp on builtin function appendappendLappendobject None append object to endLappend1L1With the interpreter documentation is never far from the student as they are programmingThere are also good IDEs for Python IDLE is a crossplatform IDE for Python that is written in Python using Tkinter Emacs users will be happy to know that there is a very good Python mode for Emacs All of these programming environments provide syntax highlighting autoindenting and access to the interactive interpreter while coding Consultthe Python wikifor a full list of Python editing environmentsIf you want to discuss Pythons use in education you may be interested in joiningthe edusig mailing list
Is python a good language for beginning programmers?
When he began implementing Python Guido van Rossum was also reading the published scripts fromMonty Pythons Flying Circus a BBC comedy series from the 1970s Van Rossum thought he needed a name that was short unique and slightly mysterious so he decided to call the language Python
Why is it called python?
To report a bug or submit a patch use the issue tracker athttpsgithubcompythoncpythonissuesFor more information on how Python is developed consultthe Python Developers Guide
How do i submit bug reports and patches for python?
Python versions are numbered ABC or ABAis the major version number it is only incremented for really major changes in the languageBis the minor version number it is incremented for less earthshattering changesCis the micro version number it is incremented for each bugfix releaseSeePEP 6for more information about bugfix releasesNot all releases are bugfix releases In the runup to a new feature release a series of development releases are made denoted as alpha beta or release candidate Alphas are early releases in which interfaces arent yet finalized its not unexpected to see an interface change between two alpha releases Betas are more stable preserving existing interfaces but possibly adding new modules and release candidates are frozen making no changes except as needed to fix critical bugsAlpha beta and release candidate versions have an additional suffixThe suffix for an alpha version is aN for some small numberNThe suffix for a beta version is bN for some small numberNThe suffix for a release candidate version is rcN for some small numberNIn other words all versions labeled20aNprecede the versions labeled20bN which precede versions labeled20rcN andthoseprecede 20You may also find version numbers with a suffix eg 22 These are unreleased versions built directly from the CPython development repository In practice after a final minor release is made the version is incremented to the next minor version which becomes the a0 version eg 24a0See also the documentation forsysversionsyshexversion andsysversioninfo
How does the python version numbering scheme work?
There are probably millions of users though its difficult to obtain an exact countPython is available for free download so there are no sales figures and its available from many different sites and packaged with many Linux distributions so download statistics dont tell the whole story eitherThe complangpython newsgroup is very active but not all Python users post to the group or even read it
How many people are using python?
There is a newsgroupcomplangpython and a mailing listpythonlist The newsgroup and mailing list are gatewayed into each other if you can read news its unnecessary to subscribe to the mailing listcomplangpythonis hightraffic receiving hundreds of postings every day and Usenet readers are often more able to cope with this volumeAnnouncements of new software releases and events can be found in complangpythonannounce a lowtraffic moderated list that receives about five postings per day Its available asthe pythonannounce mailing listMore info about other mailing lists and newsgroups can be found athttpswwwpythonorgcommunitylists
Is there a newsgroup or mailing list devoted to python?
Heres averybrief summary of what started it all written by Guido van RossumI had extensive experience with implementing an interpreted language in the ABC group at CWI and from working with this group I had learned a lot about language design This is the origin of many Python features including the use of indentation for statement grouping and the inclusion of veryhighlevel data types although the details are all different in PythonI had a number of gripes about the ABC language but also liked many of its features It was impossible to extend the ABC language or its implementation to remedy my complaints in fact its lack of extensibility was one of its biggest problems I had some experience with using Modula2 and talked with the designers of Modula3 and read the Modula3 report Modula3 is the origin of the syntax and semantics used for exceptions and some other Python featuresI was working in the Amoeba distributed operating system group at CWI We needed a better way to do system administration than by writing either C programs or Bourne shell scripts since Amoeba had its own system call interface which wasnt easily accessible from the Bourne shell My experience with error handling in Amoeba made me acutely aware of the importance of exceptions as a programming language featureIt occurred to me that a scripting language with a syntax like ABC but with access to the Amoeba system calls would fill the need I realized that it would be foolish to write an Amoebaspecific language so I decided that I needed a language that was generally extensibleDuring the 1989 Christmas holidays I had a lot of time on my hand so I decided to give it a try During the next year while still mostly working on it in my own time Python was used in the Amoeba project with increasing success and the feedback from colleagues made me add many early improvementsIn February 1991 after just over a year of development I decided to post to USENET The rest is in theMiscHISTORYfile
Why was python created in the first place?
The Python Software Foundation is an independent nonprofit organization that holds the copyright on Python versions 21 and newer The PSFs mission is to advance open source technology related to the Python programming language and to publicize the use of Python The PSFs home page is athttpswwwpythonorgpsfDonations to the PSF are taxexempt in the US If you use Python and find it helpful please contribute viathe PSF donation page
What is the python software foundation?
The standard documentation for the current stable version of Python is available athttpsdocspythonorg3 PDF plain text and downloadable HTML versions are also available athttpsdocspythonorg3downloadhtmlThe documentation is written in reStructuredText and processed bythe Sphinx documentation tool The reStructuredText source for the documentation is part of the Python source distribution
How do i get documentation on python?
Collect the arguments using theandspecifiers in the functions parameter list this gives you the positional arguments as a tuple and the keyword arguments as a dictionary You can then pass these arguments when calling another function by usinganddeffxargskwargskwargswidth143cgxargskwargs
How can i pass optional or keyword parameters from one function to another?
To specify an octal digit precede the octal value with a zero and then a lower or uppercase o For example to set the variable a to the octal value 10 8 in decimal typea0o10a8Hexadecimal is just as easy Simply precede the hexadecimal number with a zero and then a lower or uppercase x Hexadecimal digits can be specified in lower or uppercase For example in the Python interpretera0xa5a165b0XB2b178
How do i specify hexadecimal and octal integers?
To convert eg the number144to the string144 use the builtin type constructorstr If you want a hexadecimal or octal representation use the builtin functionshexoroct For fancy formatting see thefstringsandFormat String Syntaxsections eg04dformat144yields0144and3fformat1030yields0333
How do i convert a number to a string?
ou can useSrstriprnto remove all occurrences of any line terminator from the end of the stringSwithout removing other trailing whitespace If the stringSrepresents more than one line with several empty lines at the end the line terminators for all the blank lines will be removedlinesline 1rnrnrnlinesrstripnrline 1 Since this is typically only desired when reading text one line at a time usingSrstripthis way works well
Is there an equivalent to perl s chomp for removing trailing newlines from strings?
mma is not an operator in Python Consider this sessionainbaFalse aSince the comma is not an operator but a separator between expressions the above is evaluated as if you had enteredainbanotainbaThe same is true of the various assignment operators etc They are not truly operators but syntactic delimiters in assignment statements
What s up with the comma operator s precedence?
ou dont need the ability to compile Python to C code if all you want is a standalone program that users can download and run without having to install the Python distribution first There are a number of tools that determine the set of modules required by a program and bind these modules together with a Python binary to produce a single executableOne is to use the freeze tool which is included in the Python source tree asToolsfreeze It converts Python byte code to C arrays with a C compiler you can embed all your modules into a new program which is then linked with the standard Python modulesIt works by scanning your source recursively for import statements in both forms and looking for the modules in the standard Python path as well as in the source directory for builtin modules It then turns the bytecode for modules written in Python into C code array initializers that can be turned into code objects using the marshal module and creates a custommade config file that only contains those builtin modules which are actually used in the program It then compiles the generated C code and links it with the rest of the Python interpreter to form a selfcontained binary which acts exactly like your scriptThe following packages can help with the creation of console and GUI executablesNuitkaCrossplatformPyInstallerCrossplatformPyOxidizerCrossplatformcxFreezeCrossplatformpy2appmacOS onlypy2exeWindows only
How can i create a stand alone binary from a python script?
See the Python Cookbook for a long discussion of many ways to do thishttpscodeactivestatecomrecipes52560If you dont mind reordering the list sort it and then scan from the end of the list deleting duplicates as you goifmylistmylistsortlastmylist1foriinrangelenmylist211iflastmylistidelmylistielselastmylistiIf all elements of the list may be used as set keys ie they are allhashable this is often fastermylistlistsetmylistThis converts the list into a set thereby removing duplicates and then back into a list
How do you remove duplicates from a list?
The type constructortupleseqconverts any sequence actually any iterable into a tuple with the same items in the same orderFor exampletuple123yields123andtupleabcyieldsabc If the argument is a tuple it does not make a copy but returns the same object so it is cheap to calltuplewhen you arent sure that an object is already a tupleThe type constructorlistseqconverts any sequence or iterable into a list with the same items in the same order For examplelist123yields123andlistabcyieldsabc If the argument is a list it makes a copy just likeseqwould
How do i convert between tuples and lists?
ariable names with double leading underscores are mangled to provide a simple but effective way to define class private variables Any identifier of the formspamat least two leading underscores at most one trailing underscore is textually replaced withclassnamespam whereclassnameis the current class name with any leading underscores strippedThis doesnt guarantee privacy an outside user can still deliberately access the classnamespam attribute and private values are visible in the objectsdict Many Python programmers never bother to use private variable names at all
I try to use spam and i get an error about someclassname spam?
The two principal tools for caching methods arefunctoolscachedpropertyandfunctoolslrucache The former stores results at the instance level and the latter at the class levelThecachedpropertyapproach only works with methods that do not take any arguments It does not create a reference to the instance The cached method result will be kept only as long as the instance is aliveThe advantage is that when an instance is no longer used the cached method result will be released right away The disadvantage is that if instances accumulate so too will the accumulated method results They can grow without boundThelrucacheapproach works with methods that havehashablearguments It creates a reference to the instance unless special efforts are made to pass in weak referencesThe advantage of the least recently used algorithm is that the cache is bounded by the specifiedmaxsize The disadvantage is that instances are kept alive until they age out of the cache or until the cache is clearedThis example shows the various techniquesclassWeatherLookup weather information on a government websitedefinitselfstationidselfstationidstationid The stationid is private and immutabledefcurrenttemperatureselfLatest hourly observation Do not cache this because old results can be out of datecachedpropertydeflocationselfReturn the longitudelatitude coordinates of the station Result only depends on the stationidlrucachemaxsize20defhistoricrainfallselfdateunitsmmRainfall on a given date Depends on the stationid date and unitsThe above example assumes that thestationidnever changes If the relevant instance attributes are mutable thecachedpropertyapproach cant be made to work because it cannot detect changes to the attributesTo make thelrucacheapproach work when thestationidis mutable the class needs to define theeqandhashmethods so that the cache can detect relevant attribute updatesclassWeatherExample with a mutable station identifierdefinitselfstationidselfstationidstationiddefchangestationselfstationidselfstationidstationiddefeqselfotherreturnselfstationidotherstationiddefhashselfreturnhashselfstationidlrucachemaxsize20defhistoricrainfallselfdateunitscmRainfall on a given date Depends on the stationid date and units
How do i cache method calls?
For reasons of efficiency as well as consistency Python only reads the module file on the first time a module is imported If it didnt in a program consisting of many modules where each one imports the same basic module the basic module would be parsed and reparsed many times To force rereading of a changed module do thisimportimportlibimportmodnameimportlibreloadmodnameWarning this technique is not 100 foolproof In particular modules containing statements likefrommodnameimportsomeobjectswill continue to work with the old version of the imported objects If the module contains class definitions existing class instances willnotbe updated to use the new class definition This can result in the following paradoxical behaviourimportimportlibimportclscclsC Create an instance of Cimportlibreloadclsmodule cls from clspyisinstancecclsC isinstance is falseFalseThe nature of the problem is made clear if you print out the identity of the class objectshexidcclass0x7352a0hexidclsC0x4198d0
When i edit an imported module and reimport it the changes don t show up why does this happen?
Use the builtin functionisinstanceobjcls You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class egisinstanceobjclass1class2 and can also check whether an object is one of Pythons builtin types egisinstanceobjstrorisinstanceobjintfloatcomplexNote thatisinstancealso checks for virtual inheritance from anabstract base class So the test will returnTruefor a registered class even if hasnt directly or indirectly inherited from it To test for true inheritance scan theMROof the classfromcollectionsabcimportMappingclassPpassclassCPpassMappingregisterPcCisinstancecC directTrueisinstancecP indirectTrueisinstancecMapping virtualTrue Actual inheritance chaintypecmroclass C class P class object Test for true inheritanceMappingintypecmroFalseNote that most programs do not useisinstanceon userdefined classes very often If you are developing the classes yourself a more proper objectoriented style is to define methods on the classes that encapsulate a particular behaviour instead of checking the objects class and doing a different thing based on what class it is For example if you have a function that does somethingdefsearchobjifisinstanceobjMailbox code to search a mailboxelifisinstanceobjDocument code to search a documentelifA better approach is to define asearchmethod on all the classes and just call itclassMailboxdefsearchself code to search a mailboxclassDocumentdefsearchself code to search a documentobjsearch
How do i check if an object is an instance of a given class or of a subclass of it?
How do I create a pyc fileWhen a module is imported for the first time or when the source file has changed since the current compiled file was created apycfile containing the compiled code should be created in apycachesubdirectory of the directory containing thepyfile Thepycfile will have a filename that starts with the same name as thepyfile and ends withpyc with a middle component that depends on the particularpythonbinary that created it SeePEP 3147for detailsOne reason that apycfile may not be created is a permissions problem with the directory containing the source file meaning that thepycachesubdirectory cannot be created This can happen for example if you develop as one user but run as another such as if you are testing with a web serverUnless thePYTHONDONTWRITEBYTECODEenvironment variable is set creation of a pyc file is automatic if youre importing a module and Python has the ability permissions free space etc to create apycachesubdirectory and write the compiled module to that subdirectoryRunning Python on a top level script is not considered an import and nopycwill be created For example if you have a toplevel modulefoopythat imports another modulexyzpy when you runfooby typingpythonfoopyas a shell command apycwill be created forxyzbecausexyzis imported but nopycfile will be created forfoosincefoopyisnt being importedIf you need to create apycfile forfoo that is to create apycfile for a module that is not imported you can using thepycompileandcompileallmodulesThepycompilemodule can manually compile any module One way is to use thecompilefunction in that module interactivelyimportpycompilepycompilecompilefoopyThis will write thepycto apycachesubdirectory in the same location asfoopyor you can override that with the optional parametercfileYou can also automatically compile all files in a directory or directories using thecompileallmodule You can do it from the shell prompt by runningcompileallpyand providing the path of a directory containing Python files to compilepythonmcompileallHow do I find the current module nameA module can find out its own module name by looking at the predefined global variablename If this has the valuemain the program is running as a script Many modules that are usually used by importing them also provide a commandline interface or a selftest and only execute this code after checkingnamedefmainprintRunning testifnamemainmainHow can I have modules that mutually import each otherSuppose you have the following modulesfoopyfrombarimportbarvarfoovar1barpyfromfooimportfoovarbarvar2The problem is that the interpreter will perform the following stepsmain importsfooEmpty globals forfooare createdfoois compiled and starts executingfooimportsbarEmpty globals forbarare createdbaris compiled and starts executingbarimportsfoowhich is a noop since there already is a module namedfooThe import mechanism tries to readfoovarfromfooglobals to setbarfoovarfoofoovarThe last step fails because Python isnt done with interpretingfooyet and the global symbol dictionary forfoois still emptyThe same thing happens when you useimportfoo and then try to accessfoofoovarin global codeThere are at least three possible workarounds for this problemGuido van Rossum recommends avoiding all uses offrommoduleimport and placing all code inside functions Initializations of global variables and class variables should use constants or builtin functions only This means everything from an imported module is referenced asmodulenameJim Roskind suggests performing steps in the following order in each moduleexports globals functions and classes that dont need imported base classesimportstatementsactive code including globals that are initialized from imported valuesVan Rossum doesnt like this approach much because the imports appear in a strange place but it does workMatthias Urlichs recommends restructuring your code so that the recursive import is not necessary in the first placeThese solutions are not mutually exclusiveimportxyz returns module x how do I get zConsider using the convenience functionimportmodulefromimportlibinsteadzimportlibimportmodulexyzWhen I edit an imported module and reimport it the changes dont show up Why does this happenFor reasons of efficiency as well as consistency Python only reads the module file on the first time a module is imported If it didnt in a program consisting of many modules where each one imports the same basic module the basic module would be parsed and reparsed many times To force rereading of a changed module do thisimportimportlibimportmodnameimportlibreloadmodnameWarning this technique is not 100 foolproof In particular modules containing statements likefrommodnameimportsomeobjectswill continue to work with the old version of the imported objects If the module contains class definitions existing class instances willnotbe updated to use the new class definition This can result in the following paradoxical behaviourimportimportlibimportclscclsC Create an instance of Cimportlibreloadclsmodule cls from clspyisinstancecclsC isinstance is falseFalseThe nature of the problem is made clear if you print out the identity of the class objectshexidcclass0x7352a0hexidclsC0x4198d0
Modules?
eidbuiltin returns an integer that is guaranteed to be unique during the lifetime of the object Since in CPython this is the objects memory address it happens frequently that after an object is deleted from memory the next freshly created object is allocated at the same position in memory This is illustrated by this exampleid100013901272id200013901272The two ids belong to different integer objects that are created before and deleted immediately after execution of theidcall To be sure that objects whose id you want to examine are still alive create another reference to the objecta1000b2000ida13901272idb13891296
Why does the result of id appear to be not unique?
In Python variables that are only referenced inside a function are implicitly global If a variable is assigned a value anywhere within the functions body its assumed to be a local unless explicitly declared as globalThough a bit surprising at first a moments consideration explains this On one hand requiringglobalfor assigned variables provides a bar against unintended sideeffects On the other hand ifglobalwas required for all global references youd be usingglobalall the time Youd have to declare as global every reference to a builtin function or to a component of an imported module This clutter would defeat the usefulness of theglobaldeclaration for identifying sideeffects
What are the rules for local and global variables in python?
The canonical way to share information across modules within a single program is to create a special module often called config or cfg Just import the config module in all modules of your application the module then becomes available as a global name Because there is only one instance of each module any changes made to the module object get reflected everywhere For exampleconfigpyx0 Default value of the x configuration settingmodpyimportconfigconfigx1mainpyimportconfigimportmodprintconfigxNote that using a module is also the basis for implementing the singleton design pattern for the same reason
How do i share global variables across modules?
esSeveral debuggers for Python are described below and the builtin functionbreakpointallows you to drop into any of themThe pdb module is a simple but adequate consolemode debugger for Python It is part of the standard Python library and isdocumentedintheLibraryReferenceManual You can also write your own debugger by using the code for pdb as an exampleThe IDLE interactive development environment which is part of the standard Python distribution normally available asToolsscriptsidle3 includes a graphical debuggerPythonWin is a Python IDE that includes a GUI debugger based on pdb The PythonWin debugger colors breakpoints and has quite a few cool features such as debugging nonPythonWin programs PythonWin is available as part ofpywin32project and as a part of theActivePythondistributionEricis an IDE built on PyQt and the Scintilla editing componenttrepan3kis a gdblike debuggerVisual Studio Codeis an IDE with debugging tools that integrates with versioncontrol softwareThere are a number of commercial Python IDEs that include graphical debuggers They includeWing IDEKomodo IDEPyCharm
Is there a source code level debugger with breakpoints single stepping etc?
Delegation is an object oriented technique also called a design pattern Lets say you have an objectxand want to change the behaviour of just one of its methods You can create a new class that provides a new implementation of the method youre interested in changing and delegates all other methods to the corresponding method ofxPython programmers can easily implement delegation For example the following class implements a class that behaves like a file but converts all written data to uppercaseclassUpperOutdefinitselfoutfileselfoutfileoutfiledefwriteselfsselfoutfilewritesupperdefgetattrselfnamereturngetattrselfoutfilenameHere theUpperOutclass redefines thewritemethod to convert the argument string to uppercase before calling the underlyingselfoutfilewritemethod All other methods are delegated to the underlyingselfoutfileobject The delegation is accomplished via thegetattrmethod consultthe language referencefor more information about controlling attribute accessNote that for more general cases delegation can get trickier When attributes must be set as well as retrieved the class must define asetattrmethod too and it must do so carefully The basic implementation ofsetattris roughly equivalent to the followingclassXdefsetattrselfnamevalueselfdictnamevalueMostsetattrimplementations must modifyselfdictto store local state for self without causing an infinite recursion
What is delegation?
When subclassing an immutable type override thenewmethod instead of theinitmethod The latter only runsafteran instance is created which is too late to alter data in an immutable instanceAll of these immutable classes have a different signature than their parent classfromdatetimeimportdateclassFirstOfMonthDatedateAlways choose the first day of the monthdefnewclsyearmonthdayreturnsupernewclsyearmonth1classNamedIntintAllow text names for some numbersxlatzero0one1ten10defnewclsvaluevalueclsxlatgetvaluevaluereturnsupernewclsvalueclassTitleStrstrConvert str to name suitable for a URL pathdefnewclsssslowerreplace sjoincforcinsifcisalnumorcreturnsupernewclssThe classes can be used like thisFirstOfMonthDate2012214FirstOfMonthDate2012 2 1NamedIntten10NamedInt2020TitleStrBlog Why Python Rocksblogwhypythonrocks
How can a subclass control what data is stored in an immutable instance?
Use the builtinsuperfunctionclassDerivedBasedefmethselfsupermeth calls BasemethIn the examplesuperwill automatically determine the instance from which it was called theselfvalue look up themethod resolution orderMRO withtypeselfmro and return the next in line afterDerivedin the MROBase
How do i call a method defined in a base class from a derived class that extends it?
Suppose you have the following modulesfoopyfrombarimportbarvarfoovar1barpyfromfooimportfoovarbarvar2The problem is that the interpreter will perform the following stepsmain importsfooEmpty globals forfooare createdfoois compiled and starts executingfooimportsbarEmpty globals forbarare createdbaris compiled and starts executingbarimportsfoowhich is a noop since there already is a module namedfooThe import mechanism tries to readfoovarfromfooglobals to setbarfoovarfoofoovarThe last step fails because Python isnt done with interpretingfooyet and the global symbol dictionary forfoois still emptyThe same thing happens when you useimportfoo and then try to accessfoofoovarin global codeThere are at least three possible workarounds for this problemGuido van Rossum recommends avoiding all uses offrommoduleimport and placing all code inside functions Initializations of global variables and class variables should use constants or builtin functions only This means everything from an imported module is referenced asmodulenameJim Roskind suggests performing steps in the following order in each moduleexports globals functions and classes that dont need imported base classesimportstatementsactive code including globals that are initialized from imported valuesVan Rossum doesnt like this approach much because the imports appear in a strange place but it does workMatthias Urlichs recommends restructuring your code so that the recursive import is not necessary in the first placeThese solutions are not mutually exclusive
How can i have modules that mutually import each other?
A module can find out its own module name by looking at the predefined global variablename If this has the valuemain the program is running as a script Many modules that are usually used by importing them also provide a commandline interface or a selftest and only execute this code after checkingnamedefmainprintRunning testifnamemainmain
How do i find the current module name?
3Its primarily driven by the desire thatijhave the same sign asj If you want that and also wantiijjijthen integer division has to return the floor C also requires that identity to hold and then compilers that truncateijneed to makeijhave the same sign asiThere are few real use cases forijwhenjis negative Whenjis positive there are many and in virtually all of them its more useful forijto be0 If the clock says 10 now what did it say 200 hours ago190122is useful1901210is a bug waiting to bite
Why does 22 10 return 3?
A raw string ending with an odd number of backslashes will escape the strings quoterCthiswillnotworkFilestdin line1rCthiswillnotworkSyntaxErrorunterminated string literal detected at line 1There are several workarounds for this One is to use regular strings and double the backslashesCthiswillworkCthiswillworkAnother is to concatenate a regular string containing an escaped backslash to the raw stringrCthiswillworkCthiswillworkIt is also possible to useospathjointo append a backslash on WindowsospathjoinrCthiswillworkCthiswillworkNote that while a backslash will escape a quote for the purposes of determining where the raw string ends no escaping occurs when interpreting the value of the raw string That is the backslash remains present in the value of the raw stringrbackslashpreservedbackslashpreservedAlso see the specification in thelanguage reference
Can i end a raw string with an odd number of backslashes?
There are several possible reasons for thisThedelstatement does not necessarily calldel it simply decrements the objects reference count and if this reaches zerodelis calledIf your data structures contain circular links eg a tree where each child has a parent reference and each parent has a list of children the reference counts will never go back to zero Once in a while Python runs an algorithm to detect such cycles but the garbage collector might run some time after the last reference to your data structure vanishes so yourdelmethod may be called at an inconvenient and random time This is inconvenient if youre trying to reproduce a problem Worse the order in which objectsdelmethods are executed is arbitrary You can rungccollectto force a collection but therearepathological cases where objects will never be collectedDespite the cycle collector its still a good idea to define an explicitclosemethod on objects to be called whenever youre done with them Theclosemethod can then remove attributes that refer to subobjects Dont calldeldirectly delshould callcloseandcloseshould make sure that it can be called more than once for the same objectAnother way to avoid cyclical references is to use theweakrefmodule which allows you to point to objects without incrementing their reference count Tree data structures for instance should use weak references for their parent and sibling references if they need themFinally if yourdelmethod raises an exception a warning message is printed tosysstderr
My class defines del but it is not called when i delete the object?
It can be a surprise to get theUnboundLocalErrorin previously working code when it is modified by adding an assignment statement somewhere in the body of a functionThis codex10defbarprintxbar10works but this codex10deffooprintxx1results in anUnboundLocalErrorfooTraceback most recent call lastUnboundLocalErrorlocal variable x referenced before assignmentThis is because when you make an assignment to a variable in a scope that variable becomes local to that scope and shadows any similarly named variable in the outer scope Since the last statement in foo assigns a new value tox the compiler recognizes it as a local variable Consequently when the earlierprintxattempts to print the uninitialized local variable and an error resultsIn the example above you can access the outer scope variable by declaring it globalx10deffoobarglobalxprintxx1foobar10This explicit declaration is required in order to remind you that unlike the superficially analogous situation with class and instance variables you are actually modifying the value of the variable in the outer scopeprintx11You can do a similar thing in a nested scope using thenonlocalkeyworddeffoox10defbarnonlocalxprintxx1barprintxfoo1011
Why am i getting an unboundlocalerror when the variable has a value?
If you wrote code likexyxyappend10y10x10you might be wondering why appending an element toychangedxtooThere are two factors that produce this resultVariables are simply names that refer to objects Doingyxdoesnt create a copy of the list it creates a new variableythat refers to the same objectxrefers to This means that there is only one object the list and bothxandyrefer to itLists aremutable which means that you can change their contentAfter the call toappend the content of the mutable object has changed fromto10 Since both the variables refer to the same object using either name accesses the modified value10If we instead assign an immutable object toxx5 ints are immutableyxxx1 5 cant be mutated we are creating a new object herex6y5we can see that in this casexandyare not equal anymore This is because integers areimmutable and when we doxx1we are not mutating the int5by incrementing its value instead we are creating a new object the int6 and assigning it toxthat is changing which objectxrefers to After this assignment we have two objects the ints6and5 and two variables that refer to them xnow refers to6butystill refers to5Some operations for exampleyappend10andysort mutate the object whereas superficially similar operations for exampleyy10andsortedy create a new object In general in Python and in all cases in the standard library a method that mutates an object will returnNoneto help avoid getting the two types of operations confused So if you mistakenly writeysortthinking it will give you a sorted copy ofy youll instead end up withNone which will likely cause your program to generate an easily diagnosed errorHowever there is one class of operations where the same operation sometimes has different behaviors with different types the augmented assignment operators For examplemutates lists but not tuples or ints alist123is equivalent toalistextend123and mutatesalist whereassometuple123andsomeint1create new objectsIn other wordsIf we have a mutable object listdictset etc we can use some specific operations to mutate it and all the variables that refer to it will see the changeIf we have an immutable object strinttuple etc all the variables that refer to it will always see the same value but operations that transform that value into a new value always return a new objectIf you want to know if two variables refer to the same object or not you can use theisoperator or the builtin functionid
Why did changing list y also change list x?
Use thereversedbuiltin functionforxinreversedsequence do something with x This wont touch your original sequence but build a new copy with reversed order to iterate over
How do i iterate over a sequence in reverse order?
When a module is imported for the first time or when the source file has changed since the current compiled file was created apycfile containing the compiled code should be created in apycachesubdirectory of the directory containing thepyfile Thepycfile will have a filename that starts with the same name as thepyfile and ends withpyc with a middle component that depends on the particularpythonbinary that created it SeePEP 3147for detailsOne reason that apycfile may not be created is a permissions problem with the directory containing the source file meaning that thepycachesubdirectory cannot be created This can happen for example if you develop as one user but run as another such as if you are testing with a web serverUnless thePYTHONDONTWRITEBYTECODEenvironment variable is set creation of a pyc file is automatic if youre importing a module and Python has the ability permissions free space etc to create apycachesubdirectory and write the compiled module to that subdirectoryRunning Python on a top level script is not considered an import and nopycwill be created For example if you have a toplevel modulefoopythat imports another modulexyzpy when you runfooby typingpythonfoopyas a shell command apycwill be created forxyzbecausexyzis imported but nopycfile will be created forfoosincefoopyisnt being importedIf you need to create apycfile forfoo that is to create apycfile for a module that is not imported you can using thepycompileandcompileallmodulesThepycompilemodule can manually compile any module One way is to use thecompilefunction in that module interactivelyimportpycompilepycompilecompilefoopyThis will write thepycto apycachesubdirectory in the same location asfoopyor you can override that with the optional parametercfileYou can also automatically compile all files in a directory or directories using thecompileallmodule You can do it from the shell prompt by runningcompileallpyand providing the path of a directory containing Python files to compilepythonmcompileall
How do i create a pyc file?
his is because of a combination of the fact that augmented assignment operators areassignmentoperators and the difference between mutable and immutable objects in PythonThis discussion applies in general when augmented assignment operators are applied to elements of a tuple that point to mutable objects but well use alistandas our exemplarIf you wroteatuple12atuple01Traceback most recent call lastTypeErrortuple object does not support item assignmentThe reason for the exception should be immediately clear1is added to the objectatuple0points to 1 producing the result object2 but when we attempt to assign the result of the computation2 to element0of the tuple we get an error because we cant change what an element of a tuple points toUnder the covers what this augmented assignment statement is doing is approximately thisresultatuple01atuple0resultTraceback most recent call lastTypeErrortuple object does not support item assignmentIt is the assignment part of the operation that produces the error since a tuple is immutableWhen you write something likeatuplefoobaratuple0itemTraceback most recent call lastTypeErrortuple object does not support item assignmentThe exception is a bit more surprising and even more surprising is the fact that even though there was an error the append workedatuple0foo itemTo see why this happens you need to know that a if an object implements aniaddmagic method it gets called when theaugmented assignment is executed and its return value is what gets used in the assignment statement and b for listsiaddis equivalent to callingextendon the list and returning the list Thats why we say that for listsis a shorthand forlistextendalistalist1alist1This is equivalent toresultalistiadd1alistresultThe object pointed to by alist has been mutated and the pointer to the mutated object is assigned back toalist The end result of the assignment is a noop since it is a pointer to the same object thatalistwas previously pointing to but the assignment still happensThus in our tuple example what is happening is equivalent toresultatuple0iadditematuple0resultTraceback most recent call lastTypeErrortuple object does not support item assignmentTheiaddsucceeds and thus the list is extended but even thoughresultpoints to the same object thatatuple0already points to that final assignment still results in an error because tuples are immutable
Why does a tuple i item raise an exception when the addition works?
sider using the convenience functionimportmodulefromimportlibinsteadzimportlibimportmodulexyz
Import x y z returns module x how do i get z?
The technique attributed to Randal Schwartz of the Perl community sorts the elements of a list by a metric which maps each element to its sort value In Python use thekeyargument for thelistsortmethodIsortedLIsortedsortkeylambdasints1015
I want to do a complicated sort can you do a schwartzian transform in python?
Generally speaking it cant because objects dont really have names Essentially assignment always binds a name to a value the same is true ofdefandclassstatements but in that case the value is a callable Consider the following codeclassApassBAaBbaprintbmainA object at 0x16D07CCprintamainA object at 0x16D07CCArguably the class has a name even though it is bound to two names and invoked through the nameBthe created instance is still reported as an instance of classA However it is impossible to say whether the instances name isaorb since both names are bound to the same valueGenerally speaking it should not be necessary for your code to know the names of particular values Unless you are deliberately writing introspective programs this is usually an indication that a change of approach might be beneficialIn complangpython Fredrik Lundh once gave an excellent analogy in answer to this questionThe same way as you get the name of that cat you found on your porch the cat object itself cannot tell you its name and it doesnt really care so the only way to find out what its called is to ask all your neighbours namespaces if its their cat objectand dont be surprised if youll find that its known by many names or no name at all
How can my code discover the name of an object?
You have two choices you can use nested scopes or you can use callable objects For example suppose you wanted to definelinearabwhich returns a functionfxthat computes the valueaxb Using nested scopesdeflinearabdefresultxreturnaxbreturnresultOr using a callable objectclasslineardefinitselfabselfaselfbabdefcallselfxreturnselfaxselfbIn both casestaxeslinear032gives a callable object wheretaxes10e60310e62The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code However note that a collection of callables can share their signature via inheritanceclassexponentiallinear init inheriteddefcallselfxreturnselfaxselfbObject can encapsulate state for several methodsclasscountervalue0defsetselfxselfvaluexdefupselfselfvalueselfvalue1defdownselfselfvalueselfvalue1countcounterincdecresetcountupcountdowncountsetHereincdecandresetact like functions which share the same counting variable
How do you make a higher order function in python?
In general dont usefrommodulenameimport Doing so clutters the importers namespace and makes it much harder for linters to detect undefined namesImport modules at the top of a file Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope Using one import per line makes it easy to add and delete module imports but using multiple imports per line uses less screen spaceIts good practice if you import modules in the following orderstandard library modules egsysosargparserethirdparty library modules anything installed in Pythons sitepackages directory egdateutilrequestsPILImagelocally developed modulesIt is sometimes necessary to move imports to a function or class to avoid problems with circular imports Gordon McMillan saysCircular imports are fine where both modules use the import module form of import They fail when the 2nd module wants to grab a name out of the first from module import name and the import is at the top level Thats because names in the 1st are not yet available because the first module is busy importing the 2ndIn this case if the second module is only used in one function then the import can easily be moved into that function By the time the import is called the first module will have finished initializing and the second module can do its importIt may also be necessary to move imports out of the top level of code if some of the modules are platformspecific In that case it may not even be possible to import all of the modules at the top of the file In this case importing the correct modules in the corresponding platformspecific code is a good optionOnly move imports into a local scope such as inside a function definition if its necessary to solve a problem such as avoiding a circular import or are trying to reduce the initialization time of a module This technique is especially helpful if many of the imports are unnecessary depending on how the program executes You may also want to move imports into a function if the modules are only ever used in that function Note that loading a module the first time may be expensive because of the one time initialization of the module but loading a module multiple times is virtually free costing only a couple of dictionary lookups Even if the module name has gone out of scope the module is probably available insysmodules
What are the best practices for using import in a module?
For integers use the builtininttype constructor egint144144 Similarlyfloatconverts to floatingpoint egfloat1441440By default these interpret the number as decimal so thatint0144144holds true andint0x144raisesValueErrorintstringbasetakes the base to convert from as a second optional argument soint0x14416324 If the base is specified as 0 the number is interpreted using Pythons rules a leading 0o indicates octal and 0x indicates a hex numberDo not use the builtin functionevalif all you need is to convert strings to numbersevalwill be significantly slower and it presents a security risk someone could pass you a Python expression that might have unwanted side effects For example someone could passimportossystemrmrfHOMEwhich would erase your home directoryevalalso has the effect of interpreting numbers as Python expressions so that egeval09gives a syntax error because Python does not allow leading 0 in a decimal number except 0
How do i convert a string to a number?
This type of bug commonly bites neophyte programmers Consider this functiondeffoomydict Danger shared reference to one dict for all callscomputesomethingmydictkeyvaluereturnmydictThe first time you call this functionmydictcontains a single item The second timemydictcontains two items because whenfoobegins executingmydictstarts out with an item already in itIt is often expected that a function call creates new objects for default values This is not what happens Default values are created exactly once when the function is defined If that object is changed like the dictionary in this example subsequent calls to the function will refer to this changed objectBy definition immutable objects such as numbers strings tuples andNone are safe from change Changes to mutable objects such as dictionaries lists and class instances can lead to confusionBecause of this feature it is good programming practice to not use mutable objects as default values Instead useNoneas the default value and inside the function check if the parameter isNoneand create a new listdictionarywhatever if it is For example dont writedeffoomydictbutdeffoomydictNoneifmydictisNonemydict create a new dict for local namespaceThis feature can be useful When you have a function thats timeconsuming to compute a common technique is to cache the parameters and the resulting value of each call to the function and return the cached value if the same value is requested again This is called memoizing and can be implemented like this Callers can only provide two parameters and optionally pass cache by keyworddefexpensivearg1arg2cacheifarg1arg2incachereturncachearg1arg2 Calculate the valueresultexpensivecomputationcachearg1arg2result Store result in the cachereturnresultYou could use a global variable containing a dictionary instead of the default value its a matter of taste
Why are default values shared between objects?
Thats a tough one in general First here are a list of things to remember before diving furtherPerformance characteristics vary across Python implementations This FAQ focuses onCPythonBehaviour can vary across operating systems especially when talking about IO or multithreadingYou should always find the hot spots in your programbeforeattempting to optimize any code see theprofilemoduleWriting benchmark scripts will allow you to iterate quickly when searching for improvements see thetimeitmoduleIt is highly recommended to have good code coverage through unit testing or any other technique before potentially introducing regressions hidden in sophisticated optimizationsThat being said there are many tricks to speed up Python code Here are some general principles which go a long way towards reaching acceptable performance levelsMaking your algorithms faster or changing to faster ones can yield much larger benefits than trying to sprinkle microoptimization tricks all over your codeUse the right data structures Study documentation for theBuiltin Typesand thecollectionsmoduleWhen the standard library provides a primitive for doing something it is likely although not guaranteed to be faster than any alternative you may come up with This is doubly true for primitives written in C such as builtins and some extension types For example be sure to use either thelistsortbuiltin method or the relatedsortedfunction to do sorting and see theSorting Techniquesfor examples of moderately advanced usageAbstractions tend to create indirections and force the interpreter to work more If the levels of indirection outweigh the amount of useful work done your program will be slower You should avoid excessive abstraction especially under the form of tiny functions or methods which are also often detrimental to readabilityIf you have reached the limit of what pure Python can allow there are tools to take you further away For exampleCythoncan compile a slightly modified version of Python code into a C extension and can be used on many different platforms Cython can take advantage of compilation and optional type annotations to make your code significantly faster than when interpreted If you are confident in your C programming skills you can alsowrite a C extension moduleyourselfSee alsoThe wiki page devoted toperformance tips
My program is too slow how do i speed it up?
strandbytesobjects are immutable therefore concatenating many strings together is inefficient as each concatenation creates a new object In the general case the total runtime cost is quadratic in the total string lengthTo accumulate manystrobjects the recommended idiom is to place them into a list and callstrjoinat the endchunksforsinmystringschunksappendsresultjoinchunksanother reasonably efficient idiom is to useioStringIOTo accumulate manybytesobjects the recommended idiom is to extend abytearrayobject using inplace concatenation theoperatorresultbytearrayforbinmybytesobjectsresultb
What is the most efficient way to concatenate many strings together?
As with removing duplicates explicitly iterating in reverse with a delete condition is one possibility However it is easier and faster to use slice replacement with an implicit or explicit forward iteration Here are three variationsmylistfilterkeepfunctionmylistmylistxforxinmylistifkeepconditionmylistxforxinmylistifkeepconditionThe list comprehension may be fastest
How do you remove multiple items from a list?
A method is a function on some objectxthat you normally call asxnamearguments Methods are defined as functions inside the class definitionclassCdefmethselfargreturnarg2selfattribute
What is a method?
es Usually this is done by nestinglambdawithinlambda See the following three examples slightly adapted from Ulf Barteltfromfunctoolsimportreduce Primes 1000printlistfilterNonemaplambdayyreducelambdaxyxy0maplambdaxyyyxrange2intpowy0511range21000 First 10 Fibonacci numbersprintlistmaplambdaxflambdaxffx1ffx2fifx1else1fxfrange10 Mandelbrot setprintlambdaRuRoIuIoIMSxSyreducelambdaxyxnymaplambdayIuIuIoIoRuRuRoRoSySyLlambdaycIuIuIoIoRuRuRoRoiIMSxSxSySyreducelambdaxyxymaplambdaxxcRuycycRuRuRoRoiiSxSxFlambdaxcycxykflambdaxcycxykfk0orxxyy40or1fxcycxxyyxc20xyyck1ffxcycxykfchr64FRuxRoRuSxyc00irangeSxLIuyIoIuSyrangeSy21071212308024 lines on screen V V columns on screen maximum of iterations range on y axis range on x axisDont try this at home kids
Is it possible to write obfuscated one liners in python?
A class is the particular object type created by executing a class statement Class objects are used as templates to create instance objects which embody both the data attributes and code methods specific to a datatypeA class can be based on one or more other classes called its base classes It then inherits the attributes and methods of its base classes This allows an object model to be successively refined by inheritance You might have a genericMailboxclass that provides basic accessor methods for a mailbox and subclasses such asMboxMailboxMaildirMailboxOutlookMailboxthat handle various specific mailbox formats
What is a class?
Merge them into an iterator of tuples sort the resulting list and then pick out the element you wantlist1whatImsortingbylist2somethingelsetosortpairsziplist1list2pairssortedpairspairsIm else by sort sorting to what somethingresultx1forxinpairsresultelse sort to something
How can i sort one list by values from another list?
Yes there is The syntax is as followsontrueifexpressionelseonfalsexy5025smallxifxyelseyBefore this syntax was introduced in Python 25 a common idiom was to use logical operatorsexpressionandontrueoronfalseHowever this idiom is unsafe as it can give wrong results whenontruehas a false boolean value Therefore it is always better to use theifelseform
Is there an equivalent of c s ternary operator?
For an instancexof a userdefined classdirxreturns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class
How can i find the methods or attributes of an object?
Use a listthis1isanarrayLists are equivalent to C or Pascal arrays in their time complexity the primary difference is that a Python list can contain objects of many different typesThearraymodule also provides methods for creating arrays of fixed types with compact representations but they are slower to index than lists Also note thatNumPyand other third party packages define arraylike structures with various characteristics as wellTo get Lispstyle linked lists you can emulatecons cellsusing tupleslisplistlikethisexampleNoneIf mutability is desired you could use lists instead of tuples Here the analogue of a Lispcarislisplist0and the analogue ofcdrislisplist1 Only do this if youre sure you really need to because its usually a lot slower than using Python lists
How do you make an array in python?
Remember that arguments are passed by assignment in Python Since assignment just creates references to objects theres no alias between an argument name in the caller and callee and so no callbyreference per se You can achieve the desired effect in a number of waysBy returning a tuple of the resultsdeffunc1abanewvalue a and b are local namesbb1 assigned to new objectsreturnab return new valuesxyoldvalue99func1xynewvalue 100This is almost always the clearest solutionBy using global variables This isnt threadsafe and is not recommendedBy passing a mutable changeable inplace objectdeffunc2aa0newvalue a references a mutable lista1a11 changes a shared objectargsoldvalue99func2argsargsnewvalue 100By passing in a dictionary that gets mutateddeffunc3argsargsanewvalue args is a mutable dictionaryargsbargsb1 change it inplaceargsaoldvalueb99func3argsargsa newvalue b 100Or bundle up values in a class instanceclassNamespacedefinitselfargsforkeyvalueinargsitemssetattrselfkeyvaluedeffunc4argsargsanewvalue args is a mutable Namespaceargsbargsb1 change object inplaceargsNamespaceaoldvalueb99func4argsvarsargsa newvalue b 100Theres almost never a good reason to get this complicatedYour best choice is to return a tuple containing the multiple results
How do i write a function with output parameters call by reference?
Both static data and static methods in the sense of C or Java are supported in PythonFor static data simply define a class attribute To assign a new value to the attribute you have to explicitly use the class name in the assignmentclassCcount0 number of times Cinit calleddefinitselfCcountCcount1defgetcountselfreturnCcount or return selfcountccountalso refers toCcountfor anycsuch thatisinstancecCholds unless overridden bycitself or by some class on the baseclass search path fromcclassback toCCaution within a method of C an assignment likeselfcount42creates a new and unrelated instance named count inselfs own dict Rebinding of a classstatic data name must always specify the class whether inside a method or notCcount314Static methods are possibleclassCstaticmethoddefstaticarg1arg2arg3 No self parameterHowever a far more straightforward way to get the effect of a static method is via a simple modulelevel functiondefgetcountreturnCcountIf your code is structured so as to define one class or tightly related class hierarchy per module this supplies the desired encapsulation
How do i create static class data and static class methods?
In general trycopycopyorcopydeepcopyfor the general case Not all objects can be copied but most canSome objects can be copied more easily Dictionaries have acopymethodnewdictolddictcopySequences can be copied by slicingnewll
How do i copy an object in python?
nSee theUnicode HOWTO
What does unicodedecodeerror or unicodeencodeerror error mean?
ython sequences are indexed with positive numbers and negative numbers For positive numbers 0 is the first index 1 is the second index and so forth For negative indices 1 is the last index and 2 is the penultimate next to last index and so forth Think ofseqnas the same asseqlenseqnUsing negative indices can be very convenient For exampleS1is all of the string except for its last character which is useful for removing the trailing newline from a string
What s a negative index?
You could assign the base class to an alias and derive from the alias Then all you have to change is the value assigned to the alias Incidentally this trick is also handy if you want to decide dynamically eg depending on availability of resources which base class to use ExampleclassBaseBaseAliasBaseclassDerivedBaseAlias
How can i organize my code to make it easier to change the base class?
Yes The coding style required for standard library modules is documented asPEP 8
Are there coding standards or a style guide for python programs?
Python does not keep track of all instances of a class or of a builtin type You can program the classs constructor to keep track of all instances by keeping a list of weak references to each instance
How do i get a list of all instances of a given class?
You probably tried to make a multidimensional array like thisANone23This looks correct if you print itANone None None None None NoneBut when you assign a value it shows up in multiple placesA005A5 None 5 None 5 NoneThe reason is that replicating a list withdoesnt create copies it only creates references to the existing objects The3creates a list containing 3 references to the same list of length two Changes to one row will show in all rows which is almost certainly not what you wantThe suggested approach is to create a list of the desired length first and then fill in each element with a newly created listANone3foriinrange3AiNone2This generates a list containing 3 different lists of length two You can also use a list comprehensionwh23ANonewforiinrangehOr you can use an extension that provides a matrix datatypeNumPyis the best known
How do i create a multidimensional list?
This answer actually applies to all methods but the question usually comes up first in the context of constructorsIn C youd writeclassCCcoutNo argumentsnCinticoutArgument is inIn Python you have to write a single constructor that catches all cases using default arguments For exampleclassCdefinitselfiNoneifiisNoneprintNo argumentselseprintArgument isiThis is not entirely equivalent but close enough in practiceYou could also try a variablelength argument list egdefinitselfargsThe same approach works for all method definitions
How can i overload constructors or methods in python?
Trying to lookup anintliteral attribute in the normal manner gives aSyntaxErrorbecause the period is seen as a decimal point1classFilestdin line11classSyntaxErrorinvalid decimal literalThe solution is to separate the literal from the period with either a space or parentheses1classclass int1classclass int
How do i get int literal attribute instead of syntaxerror?
Not as suchFor simple input parsing the easiest approach is usually to split the line into whitespacedelimited words using thesplitmethod of string objects and then convert decimal strings to numeric values usingintorfloatsplitsupports an optional sep parameter which is useful if the line uses something other than whitespace as a separatorFor more complicated input parsing regular expressions are more powerful than Cssscanfand better suited for the task
Is there a scanf or sscanf equivalent?
Assume you use a for loop to define a few different lambdas or even plain functions egsquaresforxinrange5squaresappendlambdax2This gives you a list that contains 5 lambdas that calculatex2 You might expect that when called they would return respectively0149 and16 However when you actually try you will see that they all return16squares216squares416This happens becausexis not local to the lambdas but is defined in the outer scope and it is accessed when the lambda is called not when it is defined At the end of the loop the value ofxis4 so all the functions now return42 ie16 You can also verify this by changing the value ofxand see how the results of the lambdas changex8squares264In order to avoid this you need to save the values in variables local to the lambdas so that they dont rely on the value of the globalxsquaresforxinrange5squaresappendlambdanxn2Herenxcreates a new variablenlocal to the lambda and computed when the lambda is defined so that it has the same value thatxhad at that point in the loop This means that the value ofnwill be0in the first lambda1in the second2in the third and so on Therefore each lambda will now return the correct resultsquares24squares416Note that this behaviour is not peculiar to lambdas but applies to regular functions too
Why do lambdas defined in a loop with different values all return the same result?
To call a method or function and accumulate the return values is a list alist comprehensionis an elegant solutionresultobjmethodforobjinmylistresultfunctionobjforobjinmylistTo just run the method or function without saving the return values a plainforloop will sufficeforobjinmylistobjmethodforobjinmylistfunctionobj
How do i apply a method or function to a sequence of objects?
A slash in the argument list of a function denotes that the parameters prior to it are positionalonly Positionalonly parameters are the ones without an externally usable name Upon calling a function that accepts positionalonly parameters arguments are mapped to parameters based solely on their position For exampledivmodis a function that accepts positionalonly parameters Its documentation looks like thishelpdivmodHelp on builtin function divmod in module builtinsdivmodx y Return the tuple xy xy Invariant divy mod xThe slash at the end of the parameter list means that both parameters are positionalonly Thus callingdivmodwith keyword arguments would lead to an errordivmodx3y4Traceback most recent call lastFilestdin line1 inmoduleTypeErrordivmod takes no keyword arguments
What does the slash in the parameter list of a function mean?
here are various techniquesThe best is to use a dictionary that maps strings to functions The primary advantage of this technique is that the strings do not need to match the names of the functions This is also the primary technique used to emulate a case constructdefapassdefbpassdispatchgoastopb Note lack of parens for funcsdispatchgetinput Note trailing parens to call functionUse the builtin functiongetattrimportfoogetattrfoobarNote thatgetattrworks on any object including classes class instances modules and so onThis is used in several places in the standard library like thisclassFoodefdofooselfdefdobarselffgetattrfooinstancedoopnamefUselocalsto resolve the function namedefmyFuncprinthellofnamemyFuncflocalsfnamef
How do i use strings to call functions methods?
eisoperator tests for object identity The testaisbis equivalent toidaidbThe most important property of an identity test is that an object is always identical to itselfaisaalways returnsTrue Identity tests are usually faster than equality tests And unlike equality tests identity tests are guaranteed to return a booleanTrueorFalseHowever identity tests canonlybe substituted for equality tests when object identity is assured Generally there are three circumstances where identity is guaranteed1 Assignments create new names but do not change object identity After the assignmentnewold it is guaranteed thatnewisold2 Putting an object in a container that stores object references does not change object identity After the list assignments0x it is guaranteed thats0isx3 If an object is a singleton it means that only one instance of that object can exist After the assignmentsaNoneandbNone it is guaranteed thataisbbecauseNoneis a singletonIn most other circumstances identity tests are inadvisable and equality tests are preferred In particular identity tests should not be used to check constants such asintandstrwhich arent guaranteed to be singletonsa1000b500cb500aiscFalseaPythonbPycbthonaiscFalseLikewise new instances of mutable containers are never identicalabaisbFalseIn the standard library code you will see several common patterns for correctly using identity tests1 As recommended byPEP 8 an identity test is the preferred way to check forNone This reads like plain English in code and avoids confusion with other objects that may have boolean values that evaluate to false2 Detecting optional arguments can be tricky whenNoneis a valid input value In those situations you can create a singleton sentinel object guaranteed to be distinct from other objects For example here is how to implement a method that behaves likedictpopsentinelobjectdefpopselfkeydefaultsentinelifkeyinselfvalueselfkeydelselfkeyreturnvalueifdefaultissentinelraiseKeyErrorkeyreturndefault3 Container implementations sometimes need to augment equality tests with identity tests This prevents the code from being confused by objects such asfloatNaNthat are not equal to themselvesFor example here is the implementation ofcollectionsabcSequencecontainsdefcontainsselfvalueforvinselfifvisvalueorvvaluereturnTruereturnFalse
When can i rely on identity tests with the is operator?
Parametersare defined by the names that appear in a function definition whereasargumentsare the values actually passed to a function when calling it Parameters define whatkind of argumentsa function can accept For example given the function definitiondeffuncfoobarNonekwargspassfoobarandkwargsare parameters offunc However when callingfunc for examplefunc42bar314extrasomevarthe values42314 andsomevarare arguments
What is the difference between arguments and parameters?
You cant because strings are immutable In most situations you should simply construct a new string from the various parts you want to assemble it from However if you need an object with the ability to modify inplace unicode data try using anioStringIOobject or thearraymoduleimportiosHello worldsioioStringIOssiogetvalueHello worldsioseek77siowritethere6siogetvalueHello thereimportarrayaarrayarrayusprintaarrayu Hello worlda0yprintaarrayu yello worldatounicodeyello world
How do i modify a string in place?
Self is merely a conventional name for the first argument of a method A method defined asmethselfabcshould be called asxmethabcfor some instancexof the class in which the definition occurs the called method will think it is called asmethxabcSee alsoWhy must self be used explicitly in method definitions and calls
What is self?
YesPylintandPyflakesdo basic checking that will help you catch bugs soonerStatic type checkers such asMypyPyre andPytypecan check type hints in Python source code
Are there tools to help find bugs or perform static analysis?
ython has awithstatement that wraps the execution of a block calling code on the entrance and exit from the block Some languages have a construct that looks like thiswithobja1 equivalent to obja 1totaltotal1 objtotal objtotal 1In Python such a construct would be ambiguousOther languages such as Object Pascal Delphi and C use static types so its possible to know in an unambiguous way what member is being assigned to This is the main point of static typing the compileralwaysknows the scope of every variable at compile timePython uses dynamic types It is impossible to know in advance which attribute will be referenced at runtime Member attributes may be added or removed from objects on the fly This makes it impossible to know from a simple reading what attribute is being referenced a local one a global one or a member attributeFor instance take the following incomplete snippetdeffooawithaprintxThe snippet assumes thatamust have a member attribute calledx However there is nothing in Python that tells the interpreter this What should happen ifais let us say an integer If there is a global variable namedx will it be used inside thewithblock As you see the dynamic nature of Python makes such choices much harderThe primary benefit ofwithand similar language features reduction of code volume can however easily be achieved in Python by assignment Instead offunctionargsmydictindexindexa21functionargsmydictindexindexb42functionargsmydictindexindexc63write thisreffunctionargsmydictindexindexrefa21refb42refc63This also has the sideeffect of increasing execution speed because name bindings are resolved at runtime in Python and the second version only needs to perform the resolution onceSimilar proposals that would introduce syntax to further reduce code volume such as using a leading dot have been rejected in favour of explicitness seehttpsmailpythonorgpipermailpythonideas2016May040070html
Why doesn t python have a with statement for attribute assignments?
colon is required primarily to enhance readability one of the results of the experimental ABC language Consider thisifabprintaversusifabprintaNotice how the second one is slightly easier to read Notice further how a colon sets off the example in this FAQ answer its a standard usage in EnglishAnother minor reason is that the colon makes it easier for editors with syntax highlighting they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text
Why are colons required for the if while def class statements?
There are several advantagesOne is performance knowing that a string is immutable means we can allocate space for it at creation time and the storage requirements are fixed and unchanging This is also one of the reasons for the distinction between tuples and listsAnother advantage is that strings in Python are considered as elemental as numbers No amount of activity will change the value 8 to anything else and in Python no amount of activity will change the string eight to anything else
Why are python strings immutable?
See the next question
Why am i getting strange results with simple arithmetic operations?
Python lets you add a trailing comma at the end of lists tuples and dictionaries123abcdA15B67 last trailing comma is optional but good styleThere are several reasons to allow thisWhen you have a literal value for a list tuple or dictionary spread across multiple lines its easier to add more elements because you dont have to remember to add a comma to the previous line The lines can also be reordered without creating a syntax errorAccidentally omitting the comma can lead to errors that are hard to diagnose For examplexfeefiefoofumThis list looks like it has four elements but it actually contains three fee fiefoo and fum Always adding the comma avoids this source of errorAllowing the trailing comma may also make programmatic code generation easier
Why does python allow commas at the end of lists and tuples?
or one thing this is not a C standard feature and hence its not portable Yes we know about the Boehm GC library It has bits of assembler code formostcommon platforms not for all of them and although it is mostly transparent it isnt completely transparent patches are required to get Python to work with itTraditional GC also becomes a problem when Python is embedded into other applications While in a standalone Python its fine to replace the standardmallocandfreewith versions provided by the GC library an application embedding Python may want to have itsownsubstitute formallocandfree and may not want Pythons Right now CPython works with anything that implementsmallocandfreeproperly
Why doesn t cpython use a more traditional garbage collection scheme?
ython lambda expressions cannot contain statements because Pythons syntactic framework cant handle statements nested inside expressions However in Python this is not a serious problem Unlike lambda forms in other languages where they add functionality Python lambdas are only a shorthand notation if youre too lazy to define a functionFunctions are already first class objects in Python and can be declared in a local scope Therefore the only advantage of using a lambda instead of a locally defined function is that you dont need to invent a name for the function but thats just a local variable to which the function object which is exactly the same type of object that a lambda expression yields is assigned
Why can t lambda expressions contain statements?
situations where performance matters making a copy of the list just to sort it would be wasteful Thereforelistsortsorts the list in place In order to remind you of that fact it does not return the sorted list This way you wont be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version aroundIf you want to return a new list use the builtinsortedfunction instead This function creates a new list from a provided iterable sorts it and returns it For example heres how to iterate over the keys of a dictionary in sorted orderforkeyinsortedmydict do whatever with mydictkey
Why doesn t list sort return the sorted list?
tarting in Python 38 you canAssignment expressions using the walrus operatorassign a variable in an expressionwhilechunkfpread200printchunkSeePEP 572for more information
Why can t i use an assignment in an expression?