python-faq / output.jsonl
Saravanan666's picture
Upload output.jsonl
8b8669b verified
raw
history blame contribute delete
No virus
151 kB
{"Answer": "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", "Question": "Are there any published articles about python that i can reference?"}
{"Answer": "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", "Question": "I ve never programmed before is there a python tutorial?"}
{"Answer": "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", "Question": "How do i get a beta test version of python?"}
{"Answer": "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", "Question": "Is it reasonable to propose incompatible changes to python?"}
{"Answer": "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", "Question": "What new developments are expected for python in the future?"}
{"Answer": "e Python projects infrastructure is located all over the world and is managed by the Python Infrastructure Team Detailshere", "Question": "Where in the world is www python org located?"}
{"Answer": "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", "Question": "What is python?"}
{"Answer": "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", "Question": "How stable is python?"}
{"Answer": "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", "Question": "How do i obtain a copy of the python source?"}
{"Answer": "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", "Question": "What is python good for?"}
{"Answer": "o but it helps ", "Question": "Do i have to like monty python s flying circus?"}
{"Answer": "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", "Question": "Are there any books on python?"}
{"Answer": "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", "Question": "Have any significant projects been done in python?"}
{"Answer": "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", "Question": "Are there copyright restrictions on the use of python?"}
{"Answer": "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", "Question": "Is python a good language for beginning programmers?"}
{"Answer": "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", "Question": "Why is it called python?"}
{"Answer": "To report a bug or submit a patch use the issue tracker athttpsgithubcompythoncpythonissuesFor more information on how Python is developed consultthe Python Developers Guide", "Question": "How do i submit bug reports and patches for python?"}
{"Answer": "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", "Question": "How does the python version numbering scheme work?"}
{"Answer": "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", "Question": "How many people are using python?"}
{"Answer": "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", "Question": "Is there a newsgroup or mailing list devoted to python?"}
{"Answer": "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", "Question": "Why was python created in the first place?"}
{"Answer": "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", "Question": "What is the python software foundation?"}
{"Answer": "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", "Question": "How do i get documentation on python?"}
{"Answer": "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", "Question": "How can i pass optional or keyword parameters from one function to another?"}
{"Answer": "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", "Question": "How do i specify hexadecimal and octal integers?"}
{"Answer": "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", "Question": "How do i convert a number to a string?"}
{"Answer": "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", "Question": "Is there an equivalent to perl s chomp for removing trailing newlines from strings?"}
{"Answer": "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", "Question": "What s up with the comma operator s precedence?"}
{"Answer": "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", "Question": "How can i create a stand alone binary from a python script?"}
{"Answer": "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", "Question": "How do you remove duplicates from a list?"}
{"Answer": "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", "Question": "How do i convert between tuples and lists?"}
{"Answer": "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", "Question": "I try to use spam and i get an error about someclassname spam?"}
{"Answer": "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", "Question": "How do i cache method calls?"}
{"Answer": "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", "Question": "When i edit an imported module and reimport it the changes don t show up why does this happen?"}
{"Answer": "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", "Question": "How do i check if an object is an instance of a given class or of a subclass of it?"}
{"Answer": "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", "Question": "Modules?"}
{"Answer": "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", "Question": "Why does the result of id appear to be not unique?"}
{"Answer": "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", "Question": "What are the rules for local and global variables in python?"}
{"Answer": "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", "Question": "How do i share global variables across modules?"}
{"Answer": "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", "Question": "Is there a source code level debugger with breakpoints single stepping etc?"}
{"Answer": "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", "Question": "What is delegation?"}
{"Answer": "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", "Question": "How can a subclass control what data is stored in an immutable instance?"}
{"Answer": "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", "Question": "How do i call a method defined in a base class from a derived class that extends it?"}
{"Answer": "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", "Question": "How can i have modules that mutually import each other?"}
{"Answer": "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", "Question": "How do i find the current module name?"}
{"Answer": "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", "Question": "Why does 22 10 return 3?"}
{"Answer": "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", "Question": "Can i end a raw string with an odd number of backslashes?"}
{"Answer": "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", "Question": "My class defines del but it is not called when i delete the object?"}
{"Answer": "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", "Question": "Why am i getting an unboundlocalerror when the variable has a value?"}
{"Answer": "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", "Question": "Why did changing list y also change list x?"}
{"Answer": "Use thereversedbuiltin functionforxinreversedsequence do something with x This wont touch your original sequence but build a new copy with reversed order to iterate over", "Question": "How do i iterate over a sequence in reverse order?"}
{"Answer": "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", "Question": "How do i create a pyc file?"}
{"Answer": "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", "Question": "Why does a tuple i item raise an exception when the addition works?"}
{"Answer": "sider using the convenience functionimportmodulefromimportlibinsteadzimportlibimportmodulexyz", "Question": "Import x y z returns module x how do i get z?"}
{"Answer": "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", "Question": "I want to do a complicated sort can you do a schwartzian transform in python?"}
{"Answer": "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", "Question": "How can my code discover the name of an object?"}
{"Answer": "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", "Question": "How do you make a higher order function in python?"}
{"Answer": "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", "Question": "What are the best practices for using import in a module?"}
{"Answer": "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", "Question": "How do i convert a string to a number?"}
{"Answer": "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", "Question": "Why are default values shared between objects?"}
{"Answer": "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", "Question": "My program is too slow how do i speed it up?"}
{"Answer": "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", "Question": "What is the most efficient way to concatenate many strings together?"}
{"Answer": "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", "Question": "How do you remove multiple items from a list?"}
{"Answer": "A method is a function on some objectxthat you normally call asxnamearguments Methods are defined as functions inside the class definitionclassCdefmethselfargreturnarg2selfattribute", "Question": "What is a method?"}
{"Answer": "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", "Question": "Is it possible to write obfuscated one liners in python?"}
{"Answer": "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", "Question": "What is a class?"}
{"Answer": "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", "Question": "How can i sort one list by values from another list?"}
{"Answer": "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", "Question": "Is there an equivalent of c s ternary operator?"}
{"Answer": "For an instancexof a userdefined classdirxreturns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class", "Question": "How can i find the methods or attributes of an object?"}
{"Answer": "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", "Question": "How do you make an array in python?"}
{"Answer": "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", "Question": "How do i write a function with output parameters call by reference?"}
{"Answer": "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", "Question": "How do i create static class data and static class methods?"}
{"Answer": "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", "Question": "How do i copy an object in python?"}
{"Answer": "nSee theUnicode HOWTO", "Question": "What does unicodedecodeerror or unicodeencodeerror error mean?"}
{"Answer": "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", "Question": "What s a negative index?"}
{"Answer": "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", "Question": "How can i organize my code to make it easier to change the base class?"}
{"Answer": "Yes The coding style required for standard library modules is documented asPEP 8", "Question": "Are there coding standards or a style guide for python programs?"}
{"Answer": "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", "Question": "How do i get a list of all instances of a given class?"}
{"Answer": "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", "Question": "How do i create a multidimensional list?"}
{"Answer": "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", "Question": "How can i overload constructors or methods in python?"}
{"Answer": "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", "Question": "How do i get int literal attribute instead of syntaxerror?"}
{"Answer": "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", "Question": "Is there a scanf or sscanf equivalent?"}
{"Answer": "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", "Question": "Why do lambdas defined in a loop with different values all return the same result?"}
{"Answer": "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", "Question": "How do i apply a method or function to a sequence of objects?"}
{"Answer": "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", "Question": "What does the slash in the parameter list of a function mean?"}
{"Answer": "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", "Question": "How do i use strings to call functions methods?"}
{"Answer": "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", "Question": "When can i rely on identity tests with the is operator?"}
{"Answer": "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", "Question": "What is the difference between arguments and parameters?"}
{"Answer": "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", "Question": "How do i modify a string in place?"}
{"Answer": "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", "Question": "What is self?"}
{"Answer": "YesPylintandPyflakesdo basic checking that will help you catch bugs soonerStatic type checkers such asMypyPyre andPytypecan check type hints in Python source code", "Question": "Are there tools to help find bugs or perform static analysis?"}
{"Answer": "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", "Question": "Why doesn t python have a with statement for attribute assignments?"}
{"Answer": " 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", "Question": "Why are colons required for the if while def class statements?"}
{"Answer": "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", "Question": "Why are python strings immutable?"}
{"Answer": "See the next question", "Question": "Why am i getting strange results with simple arithmetic operations?"}
{"Answer": "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", "Question": "Why does python allow commas at the end of lists and tuples?"}
{"Answer": "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", "Question": "Why doesn t cpython use a more traditional garbage collection scheme?"}
{"Answer": "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", "Question": "Why can t lambda expressions contain statements?"}
{"Answer": " 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", "Question": "Why doesn t list sort return the sorted list?"}
{"Answer": "tarting in Python 38 you canAssignment expressions using the walrus operatorassign a variable in an expressionwhilechunkfpread200printchunkSeePEP 572for more information", "Question": "Why can t i use an assignment in an expression?"}
{"Answer": "sers are often surprised by results like this1210019999999999999996and think it is a bug in Python Its not This has little to do with Python and much more to do with how the underlying platform handles floatingpoint numbersThefloattype in CPython uses a Cdoublefor storage Afloatobjects value is stored in binary floatingpoint with a fixed precision typically 53 bits and Python uses C operations which in turn rely on the hardware implementation in the processor to perform floatingpoint operations This means that as far as floatingpoint operations are concerned Python behaves like many popular languages including C and JavaMany numbers that can be written easily in decimal notation cannot be expressed exactly in binary floatingpoint For example afterx12the value stored forxis a very good approximation to the decimal value12 but is not exactly equal to it On a typical machine the actual stored value is10011001100110011001100110011001100110011001100110011binarywhich is exactly11999999999999999555910790149937383830547332763671875decimalThe typical precision of 53 bits provides Python floats with 1516 decimal digits of accuracyFor a fuller explanation please see thefloating point arithmeticchapter in the Python tutorial", "Question": "Why are floating point calculations so inaccurate?"}
{"Answer": "CPythons lists are really variablelength arrays not Lispstyle linked lists The implementation uses a contiguous array of references to other objects and keeps a pointer to this array and the arrays length in a list head structureThis makes indexing a listaian operation whose cost is independent of the size of the list or the value of the indexWhen items are appended or inserted the array of references is resized Some cleverness is applied to improve the performance of appending items repeatedly when the array must be grown some extra space is allocated so the next few times dont require an actual resize", "Question": "How are lists implemented in cpython?"}
{"Answer": "Atryexceptblock is extremely efficient if no exceptions are raised Actually catching an exception is expensive In versions of Python prior to 20 it was common to use this idiomtryvaluemydictkeyexceptKeyErrormydictkeygetvaluekeyvaluemydictkeyThis only made sense when you expected the dict to have the key almost all the time If that wasnt the case you coded it like thisifkeyinmydictvaluemydictkeyelsevaluemydictkeygetvaluekeyFor this specific case you could also usevaluedictsetdefaultkeygetvaluekey but only if thegetvaluecall is cheap enough because it is evaluated in all cases", "Question": "How fast are exceptions?"}
{"Answer": "or technical reasons a generator used directly as a context manager would not work correctly When as is most common a generator is used as an iterator run to completion no closing is needed When it is wrap it ascontextlibclosinggeneratorin thewithstatement", "Question": "Why don t generators support the with statement?"}
{"Answer": "Strings became much more like other standard types starting in Python 16 when methods were added which give the same functionality that has always been available using the functions of the string module Most of these new methods have been widely accepted but the one which appears to make some programmers feel uncomfortable is join124816which gives the result1 2 4 8 16There are two common arguments against this usageThe first runs along the lines of It looks really ugly using a method of a string literal string constant to which the answer is that it might but a string literal is just a fixed value If the methods are to be allowed on names bound to strings there is no logical reason to make them unavailable on literalsThe second objection is typically cast as I am really telling a sequence to join its members together with a string constant Sadly you arent For some reason there seems to be much less difficulty with havingsplitas a string method since in that case it is easy to see that1 2 4 8 16split is an instruction to a string literal to return the substrings delimited by the given separator or by default arbitrary runs of white spacejoinis a string method because in using it you are telling the separator string to iterate over a sequence of strings and insert itself between adjacent elements This method can be used with any argument which obeys the rules for sequence objects including any new classes you might define yourself Similar methods exist for bytes and bytearray objects", "Question": "Why is join a string method instead of a list or tuple method?"}
{"Answer": "ou can do this easily enough with a sequence ofifelifelifelse For literal values or constants within a namespace you can also use amatchcasestatementFor cases where you need to choose from a very large number of possibilities you can create a dictionary mapping case values to functions to call For examplefunctionsafunction1bfunction2cselfmethod1funcfunctionsvaluefuncFor calling methods on objects you can simplify yet further by using thegetattrbuiltin to retrieve methods with a particular nameclassMyVisitordefvisitaselfdefdispatchselfvaluemethodnamevisitstrvaluemethodgetattrselfmethodnamemethodIts suggested that you use a prefix for the method names such asvisitin this example Without such a prefix if values are coming from an untrusted source an attacker would be able to call any method on your object", "Question": "Why isn t there a switch or case statement in python?"}
{"Answer": "Guido van Rossum believes that using indentation for grouping is extremely elegant and contributes a lot to the clarity of the average Python program Most people learn to love this feature after a whileSince there are no beginend brackets there cannot be a disagreement between grouping perceived by the parser and the human reader Occasionally C programmers will encounter a fragment of code like thisifxyxyzOnly thexstatement is executed if the condition is true but the indentation leads many to believe otherwise Even experienced C programmers will sometimes stare at it a long time wondering as to whyyis being decremented even forxyBecause there are no beginend brackets Python is much less prone to codingstyle conflicts In C there are many different ways to place the braces After becoming used to reading and writing code using a particular style it is normal to feel somewhat uneasy when reading or being required to write in a different oneMany coding styles place beginend brackets on a line by themselves This makes programs considerably longer and wastes valuable screen space making it harder to get a good overview of a program Ideally a function should fit on one screen say 2030 lines 20 lines of Python can do a lot more work than 20 lines of C This is not solely due to the lack of beginend brackets the lack of declarations and the highlevel data types are also responsible but the indentationbased syntax certainly helps", "Question": "Why does python use indentation for grouping of statements?"}
{"Answer": "The details of Python memory management depend on the implementation The standard implementation of PythonCPython uses reference counting to detect inaccessible objects and another mechanism to collect reference cycles periodically executing a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved Thegcmodule provides functions to perform a garbage collection obtain debugging statistics and tune the collectors parametersOther implementations such asJythonorPyPy however can rely on a different mechanism such as a fullblown garbage collector This difference can cause some subtle porting problems if your Python code depends on the behavior of the reference counting implementationIn some Python implementations the following code which is fine in CPython will probably run out of file descriptorsforfileinverylonglistoffilesfopenfilecfread1Indeed using CPythons reference counting and destructor scheme each new assignment tofcloses the previous file With a traditional GC however those file objects will only get collected and closed at varying and possibly long intervalsIf you want to write code that will work with any Python implementation you should explicitly close the file or use thewithstatement this will work regardless of memory management schemeforfileinverylonglistoffileswithopenfileasfcfread1", "Question": "How does python manage memory?"}
{"Answer": "swer 1 Unfortunately the interpreter pushes at least one C stack frame for each Python stack frame Also extensions can call back into Python at almost random moments Therefore a complete threads implementation requires thread support for CAnswer 2 Fortunately there isStackless Python which has a completely redesigned interpreter loop that avoids the C stack", "Question": "Can t you emulate threads in the interpreter instead of relying on an os specific thread implementation?"}
{"Answer": "The hash table implementation of dictionaries uses a hash value calculated from the key value to find the key If the key were a mutable object its value could change and thus its hash could also change But since whoever changes the key object cant tell that it was being used as a dictionary key it cant move the entry around in the dictionary Then when you try to look up the same object in the dictionary it wont be found because its hash value is different If you tried to look up the old value it wouldnt be found either because the value of the object found in that hash bin would be differentIf you want a dictionary indexed with a list simply convert the list to a tuple first the functiontupleLcreates a tuple with the same entries as the listL Tuples are immutable and can therefore be used as dictionary keysSome unacceptable solutions that have been proposedHash lists by their address object ID This doesnt work because if you construct a new list with the same value it wont be found egmydict1212printmydict12would raise aKeyErrorexception because the id of the12used in the second line differs from that in the first line In other words dictionary keys should be compared using not usingisMake a copy when using a list as a key This doesnt work because the list being a mutable object could contain a reference to itself and then the copying code would run into an infinite loopAllow lists as keys but tell the user not to modify them This would allow a class of hardtotrack bugs in programs when you forgot or modified a list by accident It also invalidates an important invariant of dictionaries every value indkeysis usable as a key of the dictionaryMark lists as readonly once they are used as a dictionary key The problem is that its not just the toplevel object that could change its value you could use a tuple containing a list as a key Entering anything as a key into a dictionary would require marking all objects reachable from there as readonly and again selfreferential objects could cause an infinite loopThere is a trick to get around this if you need to but use it at your own risk You can wrap a mutable structure inside a class instance which has both aeqand ahashmethod You must then make sure that the hash value for all such wrapper objects that reside in a dictionary or other hash based structure remain fixed while the object is in the dictionary or other structureclassListWrapperdefinitselfthelistselfthelistthelistdefeqselfotherreturnselfthelistotherthelistdefhashselflselfthelistresult98767lenl555forielinenumerateltryresultresulthashel99999991001iexceptExceptionresultresult7777777i333returnresultNote that the hash computation is complicated by the possibility that some members of the list may be unhashable and also by the possibility of arithmetic overflowFurthermore it must always be the case that ifo1o2ieo1eqo2isTrue thenhasho1hasho2ieo1hasho2hash regardless of whether the object is in a dictionary or not If you fail to meet these restrictions dictionaries and other hash based structures will misbehaveIn the case ofListWrapper whenever the wrapper object is in a dictionary the wrapped list must not change to avoid anomalies Dont do this unless you are prepared to think hard about the requirements and the consequences of not meeting them correctly Consider yourself warned", "Question": "Why must dictionary keys be immutable?"}
{"Answer": "Lists and tuples while similar in many respects are generally used in fundamentally different ways Tuples can be thought of as being similar to Pascalrecordsor Cstructs theyre small collections of related data which may be of different types which are operated on as a group For example a Cartesian coordinate is appropriately represented as a tuple of two or three numbersLists on the other hand are more like arrays in other languages They tend to hold a varying number of objects all of which have the same type and which are operated on onebyone For exampleoslistdirreturns a list of strings representing the files in the current directory Functions which operate on this output would generally not break if you added another file or two to the directoryTuples are immutable meaning that once a tuple has been created you cant replace any of its elements with a new value Lists are mutable meaning that you can always change a lists elements Only immutable elements can be used as dictionary keys and hence only tuples and not lists can be used as keys", "Question": "Why are there separate tuple and list data types?"}
{"Answer": "The idea was borrowed from Modula3 It turns out to be very useful for a variety of reasonsFirst its more obvious that you are using a method or instance attribute instead of a local variable Readingselfxorselfmethmakes it absolutely clear that an instance variable or method is used even if you dont know the class definition by heart In C you can sort of tell by the lack of a local variable declaration assuming globals are rare or easily recognizable but in Python there are no local variable declarations so youd have to look up the class definition to be sure Some C and Java coding standards call for instance attributes to have anmprefix so this explicitness is still useful in those languages tooSecond it means that no special syntax is necessary if you want to explicitly reference or call the method from a particular class In C if you want to use a method from a base class which is overridden in a derived class you have to use theoperator in Python you can writebaseclassmethodnameselfargumentlist This is particularly useful forinitmethods and in general in cases where a derived class method wants to extend the base class method of the same name and thus has to call the base class method somehowFinally for instance variables it solves a syntactic problem with assignment since local variables in Python are by definition those variables to which a value is assigned in a function body and that arent explicitly declared global there has to be some way to tell the interpreter that an assignment was meant to assign to an instance variable instead of to a local variable and it should preferably be syntactic for efficiency reasons C does this through declarations but Python doesnt have declarations and it would be a pity having to introduce them just for this purpose Using the explicitselfvarsolves this nicely Similarly for using instance variables having to writeselfvarmeans that references to unqualified names inside a method dont have to search the instances directories To put it another way local variables and instance variables live in two different namespaces and you need to tell Python which namespace to use", "Question": "Why must self be used explicitly in method definitions and calls?"}
{"Answer": "bjects referenced from the global namespaces of Python modules are not always deallocated when Python exits This may happen if there are circular references There are also certain bits of memory that are allocated by the C library that are impossible to free eg a tool like Purify will complain about these Python is however aggressive about cleaning up memory on exit and does try to destroy every single objectIf you want to force Python to delete certain things on deallocation use theatexitmodule to run a function that will force those deletions", "Question": "Why isn t all memory freed when cpython exits?"}
{"Answer": "re precisely they cant end with an odd number of backslashes the unpaired backslash at the end escapes the closing quote character leaving an unterminated stringRaw strings were designed to ease creating input for processors chiefly regular expression engines that want to do their own backslash escape processing Such processors consider an unmatched trailing backslash to be an error anyway so raw strings disallow that In return they allow you to pass on the string quote character by escaping it with a backslash These rules work well when rstrings are used for their intended purposeIf youre trying to build Windows pathnames note that all Windows system calls accept forward slashes toofopenmydirfiletxt works fineIf youre trying to build a pathname for a DOS command try eg one ofdirrthisismydosdirdirrthisismydosdir 1dirthisismydosdir", "Question": "Why can t raw strings r strings end with a backslash?"}
{"Answer": "Cythoncompiles a modified version of Python with optional annotations into C extensionsNuitkais an upandcoming compiler of Python into C code aiming to support the full Python language", "Question": "Can python be compiled to machine code c or some other language?"}
{"Answer": "uido saida For some operations prefix notation just reads better than postfix prefix and infix operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem Compare the easy with which we rewrite a formula like xab into xa xb to the clumsiness of doing the same thing using a raw OO notationb When I read code that says lenx Iknowthat it is asking for the length of something This tells me two things the result is an integer and the argument is some kind of container To the contrary when I read xlen I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len Witness the confusion we occasionally have when a class that is not implementing a mapping has a get or keys method or something that isnt a file has a write methodhttpsmailpythonorgpipermailpython30002006November004643html", "Question": "Why does python use methods for some functionality e g list index but functions for other e g len list?"}
{"Answer": "CPythons dictionaries are implemented as resizable hash tables Compared to Btrees this gives better performance for lookup the most common operation by far under most circumstances and the implementation is simplerDictionaries work by computing a hash code for each key stored in the dictionary using thehashbuiltin function The hash code varies widely depending on the key and a perprocess seed for examplePythoncould hash to539294296whilepython a string that differs by a single bit could hash to1142331976 The hash code is then used to calculate a location in an internal array where the value will be stored Assuming that youre storing keys that all have different hash values this means that dictionaries take constant time O1 in BigO notation to retrieve a key", "Question": "How are dictionaries implemented in cpython?"}
{"Answer": "In the 1970s people realized that unrestricted goto could lead to messy spaghetti code that was hard to understand and revise In a highlevel language it is also unneeded as long as there are ways to branch in Python withifstatements andorand andifelseexpressions and loop withwhileandforstatements possibly containingcontinueandbreakOne can also use exceptions to provide a structured goto that works even across function calls Many feel that exceptions can conveniently emulate all reasonable uses of thegoorgotoconstructs of C Fortran and other languages For exampleclasslabelExceptionpass declare a labeltryifconditionraiselabel goto labelexceptlabel where to gotopassThis doesnt allow you to jump into the middle of a loop but thats usually considered an abuse ofgotoanyway Use sparingly", "Question": "Why is there no goto?"}
{"Answer": "An interface specification for a module as provided by languages such as C and Java describes the prototypes for the methods and functions of the module Many feel that compiletime enforcement of interface specifications helps in the construction of large programsPython 26 adds anabcmodule that lets you define Abstract Base Classes ABCs You can then useisinstanceandissubclassto check whether an instance or a class implements a particular ABC Thecollectionsabcmodule defines a set of useful ABCs such asIterableContainer andMutableMappingFor Python many of the advantages of interface specifications can be obtained by an appropriate test discipline for componentsA good test suite for a module can both provide a regression test and serve as a module interface specification and a set of examples Many Python modules can be run as a script to provide a simple self test Even modules which use complex external interfaces can often be tested in isolation using trivial stub emulations of the external interface Thedoctestandunittestmodules or thirdparty test frameworks can be used to construct exhaustive test suites that exercise every line of code in a moduleAn appropriate testing discipline can help build large complex applications in Python as well as having interface specifications would In fact it can be better because an interface specification cannot test certain properties of a program For example thelistappendmethod is expected to add new elements to the end of some internal list an interface specification cannot test that yourlistappendimplementation will actually do this correctly but its trivial to check this property in a test suiteWriting test suites is very helpful and you might want to design your code to make it easily tested One increasingly popular technique testdriven development calls for writing parts of the test suite first before you write any of the actual code Of course Python allows you to be sloppy and not write test cases at all", "Question": "How do you specify and enforce an interface spec in python?"}
{"Answer": "Use the standard library modulesmtplibHeres a very simple interactive mail sender that uses it This method will work on any host that supports an SMTP listenerimportsyssmtplibfromaddrinputFrom toaddrsinputTo splitprintEnter message end with DmsgwhileTruelinesysstdinreadlineifnotlinebreakmsgline The actual mail sendserversmtplibSMTPlocalhostserversendmailfromaddrtoaddrsmsgserverquitA Unixonly alternative uses sendmail The location of the sendmail program varies between systems sometimes it isusrlibsendmail sometimesusrsbinsendmail The sendmail manual page will help you out Heres some sample codeimportosSENDMAILusrsbinsendmail sendmail locationpospopenst iSENDMAILwpwriteTo receiverexamplecomnpwriteSubject testnpwriten blank line separating headers from bodypwriteSome textnpwritesome more textnstspcloseifsts0printSendmail exit statussts", "Question": "How do i send mail from a python script?"}
{"Answer": "he most common problem is that the signal handler is declared with the wrong argument list It is called ashandlersignumframeso it should be declared with two parametersdefhandlersignumframe", "Question": "Why don t my signal handlers work?"}
{"Answer": "Checkthe Library Referenceto see if theres a relevant standard library module Eventually youll learn whats in the standard library and will be able to skip this stepFor thirdparty packages search thePython Package Indexor tryGoogleor another web search engine Searching for Python plus a keyword or two for your topic of interest will usually find something helpful", "Question": "How do i find a module or application to perform task x?"}
{"Answer": "You need to do two things the script files mode must be executable and the first line must begin withfollowed by the path of the Python interpreterThe first is done by executingchmodxscriptfileor perhapschmod755scriptfileThe second can be done in a number of ways The most straightforward way is to writeusrlocalbinpythonas the very first line of your file using the pathname for where the Python interpreter is installed on your platformIf you would like the script to be independent of where the Python interpreter lives you can use theenvprogram Almost all Unix variants support the following assuming the Python interpreter is in a directory on the usersPATHusrbinenv pythonDontdo this for CGI scripts ThePATHvariable for CGI scripts is often very minimal so you need to use the actual absolute pathname of the interpreterOccasionally a users environment is so full that theusrbinenvprogram fails or theres no env program at all In that case you can try the following hack due to Alex Rezinsky binshexecpython01The minor disadvantage is that this defines the scripts doc string However you can fix that by addingdocWhatever", "Question": "How do i make a python script executable on unix?"}
{"Answer": "Thepydocmodule can create HTML from the doc strings in your Python source code An alternative for creating API documentation purely from docstrings isepydocSphinxcan also include docstring content", "Question": "How do i create documentation from doc strings?"}
{"Answer": "For Win32 OSX Linux BSD Jython IronPythonhttpspypiorgprojectpyserialFor Unix see a Usenet post by Mitch Chapmanhttpsgroupsgooglecomgroupsselm34A04430CF9ohioeecom", "Question": "How do i access the serial rs232 port?"}
{"Answer": "or Unix variants The standard Python source distribution comes with a curses module in theModulessubdirectory though its not compiled by default Note that this is not available in the Windows distribution there is no curses module for WindowsThecursesmodule supports basic curses features as well as many additional functions from ncurses and SYSV curses such as colour alternative character set support pads and mouse support This means the module isnt compatible with operating systems that only have BSD curses but there dont seem to be any currently maintained OSes that fall into this category", "Question": "Is there a curses termcap package for python?"}
{"Answer": "Theshutilmodule contains acopyfilefunction Note that on Windows NTFS volumes it does not copyalternate data streamsnorresource forkson macOS HFS volumes though both are now rarely used It also doesnt copy file permissions and metadata though usingshutilcopy2instead will preserve most though not all of it", "Question": "How do i copy a file?"}
{"Answer": "The standard modulerandomimplements a random number generator Usage is simpleimportrandomrandomrandomThis returns a random floating point number in the range 0 1There are also many other specialized generators in this module such asrandrangeabchooses an integer in the range a buniformabchooses a floating point number in the range a bnormalvariatemeansdevsamples the normal Gaussian distributionSome higherlevel functions operate on sequences directly such aschoiceSchooses a random element from a given sequenceshuffleLshuffles a list inplace ie permutes it randomlyTheres also aRandomclass you can instantiate to create independent multiple random number generators", "Question": "How do i generate random numbers in python?"}
{"Answer": "global interpreter lockGIL is used internally to ensure that only one thread runs in the Python VM at a time In general Python offers to switch among threads only between bytecode instructions how frequently it switches can be set viasyssetswitchinterval Each bytecode instruction and therefore all the C implementation code reached from each instruction is therefore atomic from the point of view of a Python programIn theory this means an exact accounting requires an exact understanding of the PVM bytecode implementation In practice it means that operations on shared variables of builtin data types ints lists dicts etc that look atomic really areFor example the following operations are all atomic L L1 L2 are lists D D1 D2 are dicts x y are objects i j are intsLappendxL1extendL2xLixLpopL1ijL2LsortxyxfieldyDxyD1updateD2DkeysThese arentii1LappendL1LiLjDxDx1Operations that replace other objects may invoke those other objectsdelmethod when their reference count reaches zero and that can affect things This is especially true for the mass updates to dictionaries and lists When in doubt use a mutex", "Question": "What kinds of global value mutation are thread safe?"}
{"Answer": "thonfile objectsare a highlevel layer of abstraction on lowlevel C file descriptorsFor most file objects you create in Python via the builtinopenfunctionfclosemarks the Python file object as being closed from Pythons point of view and also arranges to close the underlying C file descriptor This also happens automatically infs destructor whenfbecomes garbageBut stdin stdout and stderr are treated specially by Python because of the special status also given to them by C Runningsysstdoutclosemarks the Pythonlevel file object as being closed but doesnotclose the associated C file descriptorTo close the underlying C file descriptor for one of these three you should first be sure thats what you really want to do eg you may confuse extension modules trying to do IO If it is useoscloseosclosestdinfilenoosclosestdoutfilenoosclosestderrfilenoOr you can use the numeric constants 0 1 and 2 respectively", "Question": "Why doesn t closing sys stdout stdin stderr really close it?"}
{"Answer": "heglobal interpreter lockGIL is often seen as a hindrance to Pythons deployment on highend multiprocessor server machines because a multithreaded Python program effectively only uses one CPU due to the insistence that almost all Python code can only run while the GIL is heldBack in the days of Python 15 Greg Stein actually implemented a comprehensive patch set the free threading patches that removed the GIL and replaced it with finegrained locking Adam Olsen recently did a similar experiment in hispythonsafethreadproject Unfortunately both experiments exhibited a sharp drop in singlethread performance at least 30 slower due to the amount of finegrained locking necessary to compensate for the removal of the GILThis doesnt mean that you cant make good use of Python on multiCPU machines You just have to be creative with dividing the work up between multipleprocessesrather than multiplethreads TheProcessPoolExecutorclass in the newconcurrentfuturesmodule provides an easy way of doing so themultiprocessingmodule provides a lowerlevel API in case you want more control over dispatching of tasksJudicious use of C extensions will also help if you use a C extension to perform a timeconsuming task the extension can release the GIL while the thread of execution is in the C code and allow other threads to get some work done Some standard library modules such aszlibandhashlibalready do thisIt has been suggested that the GIL should be a perinterpreterstate lock rather than truly global interpreters then wouldnt be able to share objects Unfortunately this isnt likely to happen either It would be a tremendous amount of work because many object implementations currently have global state For example small integers and short strings are cached these caches would have to be moved to the interpreter state Other object types have their own free list these free lists would have to be moved to the interpreter state And so onAnd I doubt that it can even be done in finite time because the same problem exists for 3rd party extensions It is likely that 3rd party extensions are being written at a faster rate than you can convert them to store all their global state in the interpreter stateAnd finally once you have multiple interpreters not sharing any state what have you gained over running each interpreter in a separate process", "Question": "Can t we get rid of the global interpreter lock?"}
{"Answer": "Python comes with two testing frameworks Thedoctestmodule finds examples in the docstrings for a module and runs them comparing the output with the expected output given in the docstringTheunittestmodule is a fancier testing framework modelled on Java and Smalltalk testing frameworksTo make testing easier you should use good modular design in your program Your program should have almost all functionality encapsulated in either functions or class methods and this sometimes has the surprising and delightful effect of making the program run faster because local variable accesses are faster than global accesses Furthermore the program should avoid depending on mutating global variables since this makes testing much more difficult to doThe global main logic of your program may be as simple asifnamemainmainlogicat the bottom of the main module of your programOnce your program is organized as a tractable collection of function and class behaviours you should write test functions that exercise the behaviours A test suite that automates a sequence of tests can be associated with each module This sounds like a lot of work but since Python is so terse and flexible its surprisingly easy You can make coding much more pleasant and fun by writing your test functions in parallel with the production code since this makes it easy to find bugs and even design flaws earlierSupport modules that are not intended to be the main module of a program may include a selftest of the moduleifnamemainselftestEven programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using fake interfaces implemented in Python", "Question": "How do i test a python program or component?"}
{"Answer": "The easiest way is to use theconcurrentfuturesmodule especially theThreadPoolExecutorclassOr if you want fine control over the dispatching algorithm you can write your own logic manually Use thequeuemodule to create a queue containing a list of jobs TheQueueclass maintains a list of objects and has aputobjmethod that adds items to the queue and agetmethod to return them The class will take care of the locking necessary to ensure that each job is handed out exactly onceHeres a trivial exampleimportthreadingqueuetime The worker thread gets jobs off the queue When the queue is empty it assumes there will be no more work and exits Realistically workers will run until terminateddefworkerprintRunning workertimesleep01whileTruetryargqgetblockFalseexceptqueueEmptyprintWorkerthreadingcurrentthreadend printqueue emptybreakelseprintWorkerthreadingcurrentthreadend printrunning with argumentargtimesleep05 Create queueqqueueQueue Start a pool of 5 workersforiinrange5tthreadingThreadtargetworkernameworkerii1tstart Begin adding work to the queueforiinrange50qputi Give threads time to runprintMain thread sleepingtimesleep5When run this will produce the following outputRunning worker Running worker Running worker Running worker Running worker Main thread sleeping Worker Threadworker 1 started 130283832797456 running with argument 0 Worker Threadworker 2 started 130283824404752 running with argument 1 Worker Threadworker 3 started 130283816012048 running with argument 2 Worker Threadworker 4 started 130283807619344 running with argument 3 Worker Threadworker 5 started 130283799226640 running with argument 4 Worker Threadworker 1 started 130283832797456 running with argument 5 Consult the modules documentation for more details theQueueclass provides a featureful interface", "Question": "How do i parcel out work among a bunch of worker threads?"}
{"Answer": "For Unix variants there are several solutions Its straightforward to do this using curses but curses is a fairly large module to learn", "Question": "How do i get a single keypress at a time?"}
{"Answer": "Useosremovefilenameorosunlinkfilename for documentation see theosmodule The two functions are identicalunlinkis simply the name of the Unix system call for this functionTo remove a directory useosrmdir useosmkdirto create oneosmakedirspathwill create any intermediate directories inpaththat dont existosremovedirspathwill remove intermediate directories as long as theyre empty if you want to delete an entire directory tree and its contents useshutilrmtreeTo rename a file useosrenameoldpathnewpathTo truncate a file open it usingfopenfilenamerb and useftruncateoffset offset defaults to the current seek position Theres alsoosftruncatefdoffsetfor files opened withosopen wherefdis the file descriptor a small integerTheshutilmodule also contains a number of functions to work on files includingcopyfilecopytree andrmtree", "Question": "How do i delete a file and other file questions?"}
{"Answer": "See the chapters titledInternet Protocols and SupportandInternet Data Handlingin the Library Reference Manual Python has many modules that will help you build serverside and clientside web systemsA summary of available frameworks is maintained by Paul Boddie athttpswikipythonorgmoinWebProgrammingCameron Laird maintains a useful set of pages about Python web technologies athttpswebarchiveorgweb20210224183619httpphaseitnetclairdcomplangpythonwebpython", "Question": "What www tools are there for python?"}
{"Answer": "As soon as the main thread exits all threads are killed Your main thread is running too quickly giving the threads no time to do any workA simple fix is to add a sleep to the end of the program thats long enough for all the threads to finishimportthreadingtimedefthreadtasknamenforiinrangenprintnameiforiinrange10TthreadingThreadtargetthreadtaskargsstriiTstarttimesleep10 But now on many platforms the threads dont run in parallel but appear to run sequentially one at a time The reason is that the OS thread scheduler doesnt start a new thread until the previous thread is blockedA simple fix is to add a tiny sleep to the start of the run functiondefthreadtasknamentimesleep0001 foriinrangenprintnameiforiinrange10TthreadingThreadtargetthreadtaskargsstriiTstarttimesleep10Instead of trying to guess a good delay value fortimesleep its better to use some kind of semaphore mechanism One idea is to use thequeuemodule to create a queue object let each thread append a token to the queue when it finishes and let the main thread read as many tokens from the queue as there are threads", "Question": "None of my threads seem to run why?"}
{"Answer": "heatexitmodule provides a register function that is similar to Csonexit", "Question": "Is there an equivalent to c s onexit in python?"}
{"Answer": "Theselectmodule is commonly used to help with asynchronous IO on socketsTo prevent the TCP connect from blocking you can set the socket to nonblocking mode Then when you do theconnect you will either connect immediately unlikely or get an exception that contains the error number aserrnoerrnoEINPROGRESSindicates that the connection is in progress but hasnt finished yet Different OSes will return different values so youre going to have to check whats returned on your systemYou can use theconnectexmethod to avoid creating an exception It will just return the errno value To poll you can callconnectexagain later 0orerrnoEISCONNindicate that youre connected or you can pass this socket toselectselectto check if its writableNoteTheasynciomodule provides a general purpose singlethreaded and concurrent asynchronous library which can be used for writing nonblocking network code The thirdpartyTwistedlibrary is a popular and featurerich alternative", "Question": "How do i avoid blocking in the connect method of a socket?"}
{"Answer": "Thepicklelibrary module solves this in a very general way though you still cant store things like open files sockets or windows and theshelvelibrary module uses pickle and gdbm to create persistent mappings containing arbitrary Python objects", "Question": "How do you implement persistent objects in python?"}
{"Answer": "you cant find a source file for a module it may be a builtin or dynamically loaded module implemented in C C or other compiled language In this case you may not have the source file or it may be something likemathmodulec somewhere in a C source directory not on the Python PathThere are at least three kinds of modules in Pythonmodules written in Python pymodules written in C and dynamically loaded dll pyd so sl etcmodules written in C and linked with the interpreter to get a list of these typeimportsysprintsysbuiltinmodulenames", "Question": "Where is the math py socket py regex py etc source file?"}
{"Answer": "You can find a collection of useful links on theWeb Programming wiki page", "Question": "What module should i use to help with generating html?"}
{"Answer": "Be sure to use thethreadingmodule and not thethreadmodule Thethreadingmodule builds convenient abstractions on top of the lowlevel primitives provided by thethreadmodule", "Question": "How do i program using threads?"}
{"Answer": " would like to retrieve web pages that are the result of POSTing a form Is there existing code that would let me do this easilyYes Heres a simple example that usesurllibrequestusrlocalbinpythonimporturllibrequest build the query stringqsFirstJosephineMIQLastPublic connect and send the server a pathrequrllibrequesturlopenhttpwwwsomeserverouttherecgibinsomecgiscriptdataqswithreqmsghdrsreqreadreqinfoNote that in general for percentencoded POST operations query strings must be quoted usingurllibparseurlencode For example to sendnameGuySteeleJrimporturllibparseurllibparseurlencodenameGuy Steele JrnameGuySteele2CJrSee alsoHOWTO Fetch Internet Resources Using The urllib Packagefor extensive examples", "Question": "How can i mimic cgi form submission method post?"}
{"Answer": "YesInterfaces to diskbased hashes such asDBMandGDBMare also included with standard Python There is also thesqlite3module which provides a lightweight diskbased relational databaseSupport for most relational databases is available See theDatabaseProgramming wiki pagefor details", "Question": "Are there any interfaces to database packages in python?"}
{"Answer": "eadis a lowlevel function which takes a file descriptor a small integer representing the opened fileospopencreates a highlevel file object the same type returned by the builtinopenfunction Thus to readnbytes from a pipepcreated withospopen you need to usepreadn", "Question": "I can t seem to use os read on a pipe created with os popen why?"}
{"Answer": "To read or write complex binary data formats its best to use thestructmodule It allows you to take a string containing binary data usually numbers and convert it to Python objects and vice versaFor example the following code reads two 2byte integers and one 4byte integer in bigendian format from a fileimportstructwithopenfilenamerbasfsfread8xyzstructunpackhhlsThe in the format string forces bigendian data the letter h reads one short integer 2 bytes and l reads one long integer 4 bytes from the stringFor data that is more regular eg a homogeneous list of ints or floats you can also use thearraymoduleNoteTo read and write binary data it is mandatory to open the file in binary mode here passingrbtoopen If you userinstead the default the file will be open in text mode andfreadwill returnstrobjects rather thanbytesobjects", "Question": "How do i read or write binary data?"}
{"Answer": "You can get a pointer to the module object as followsmodulePyImportImportModulemodulenameIf the module hasnt been imported yet ie it is not yet present insysmodules this initializes the module otherwise it simply returns the value ofsysmodulesmodulename Note that it doesnt enter the module into any namespace it only ensures it has been initialized and is stored insysmodulesYou can then access the modules attributes ie any name defined in the module as followsattrPyObjectGetAttrStringmoduleattrnameCallingPyObjectSetAttrStringto assign to variables in the module also works", "Question": "How do i access a module written in python from c?"}
{"Answer": "Setup must end in a newline if there is no newline there the build process fails Fixing this requires some ugly shell script hackery and this bug is so minor that it doesnt seem worth the effort", "Question": "I added a module using the setup file and the make fails why?"}
{"Answer": "Sometimes you want to emulate the Python interactive interpreters behavior where it gives you a continuation prompt when the input is incomplete eg you typed the start of an if statement or you didnt close your parentheses or triple string quotes but it gives you a syntax error message immediately when the input is invalidIn Python you can use thecodeopmodule which approximates the parsers behavior sufficiently IDLE uses this for exampleThe easiest way to do it in C is to callPyRunInteractiveLoopperhaps in a separate thread and let the Python interpreter handle the input for you You can also set thePyOSReadlineFunctionPointerto point at your custom input function SeeModulesreadlinecandParsermyreadlinecfor more hints", "Question": "How do i tell incomplete input from invalid input?"}
{"Answer": "Call the functionPyRunStringfrom the previous question with the start symbolPyevalinput it parses an expression evaluates it and returns its value", "Question": "How can i evaluate an arbitrary python expression from c?"}
{"Answer": " Python code define an object that supports thewritemethod Assign this object tosysstdoutandsysstderr Call printerror or just allow the standard traceback mechanism to work Then the output will go wherever yourwritemethod sends itThe easiest way to do this is to use theioStringIOclassimportiosyssysstdoutioStringIOprintfooprinthello worldsysstderrwritesysstdoutgetvaluefoohello worldA custom object to do the same would look like thisimportiosysclassStdoutCatcherioTextIOBasedefinitselfselfdatadefwriteselfstuffselfdataappendstuffimportsyssysstdoutStdoutCatcherprintfooprinthello worldsysstderrwritejoinsysstdoutdatafoohello world", "Question": "How do i catch the output from pyerr print or anything that prints to stdout stderr?"}
{"Answer": "There are a number of alternatives to writing your own C extensions depending on what youre trying to doCythonand its relativePyrexare compilers that accept a slightly modified form of Python and generate the corresponding C code Cython and Pyrex make it possible to write an extension without having to learn Pythons C APIIf you need to interface to some C or C library for which no Python extension currently exists you can try wrapping the librarys data types and functions with a tool such asSWIGSIPCXXBoost orWeaveare also alternatives for wrapping C libraries", "Question": "Writing c is hard are there any alternatives?"}
{"Answer": "That depends on the objects type If its a tuplePyTupleSizereturns its length andPyTupleGetItemreturns the item at a specified index Lists have similar functionsPyListSizeandPyListGetItemFor bytesPyBytesSizereturns its length andPyBytesAsStringAndSizeprovides a pointer to its value and its length Note that Python bytes objects may contain null bytes so Csstrlenshould not be usedTo test the type of an object first make sure it isntNULL and then usePyBytesCheckPyTupleCheckPyListCheck etcThere is also a highlevel API to Python objects which is provided by the socalled abstract interface readIncludeabstracthfor further details It allows interfacing with any kind of Python sequence using calls likePySequenceLengthPySequenceGetItem etc as well as many other useful protocols such as numbers PyNumberIndexet al and mappings in the PyMapping APIs", "Question": "How do i extract c values from a python object?"}
{"Answer": " dynamically load g extension modules you must recompile Python relink it using g change LINKCC in the Python Modules Makefile and link your extension module using g eggsharedomymodulesomymoduleo", "Question": "How do i find undefined g symbols builtin new or pure virtual?"}
{"Answer": "Yes you can create builtin modules containing functions variables exceptions and even new types in C This is explained in the documentExtending and Embedding the Python InterpreterMost intermediate or advanced Python books will also cover this topic", "Question": "Can i create my own functions in c?"}
{"Answer": "ou cant UsePyTuplePackinstead", "Question": "How do i use py buildvalue to create a tuple of arbitrary length?"}
{"Answer": "Most packaged versions of Python dont include theusrlibpython2xconfigdirectory which contains various files required for compiling Python extensionsFor Red Hat install the pythondevel RPM to get the necessary filesFor Debian runaptgetinstallpythondev", "Question": "I want to compile a python module on my linux system but some files are missing why?"}
{"Answer": "The highestlevel function to do this isPyRunSimpleStringwhich takes a single string argument to be executed in the context of the modulemainand returns0for success and1when an exception occurred includingSyntaxError If you want more control usePyRunString see the source forPyRunSimpleStringinPythonpythonrunc", "Question": "How can i execute arbitrary python statements from c?"}
{"Answer": "es you can inherit from builtin classes such asintlistdict etcThe Boost Python Library BPLhttpswwwboostorglibspythondocindexhtml provides a way of doing this from C ie you can inherit from an extension class written in C using the BPL", "Question": "Can i create an object class with some methods implemented in c and others in python e g through inheritance?"}
{"Answer": " I create my own functions in CYes using the C compatibility features found in C PlaceexternCaround the Python include files and putexternCbefore each function that is going to be called by the Python interpreter Global or static C objects with constructors are probably not a good idea", "Question": "Id1?"}
{"Answer": "Depending on your requirements there are many approaches To do this manually begin by readingthe Extending and Embedding document Realize that for the Python runtime system there isnt a whole lot of difference between C and C so the strategy of building a new Python type around a C structure pointer type will also work for C objectsFor C libraries seeWriting C is hard are there any alternatives", "Question": "How do i interface to c objects from python?"}
{"Answer": "hePyObjectCallMethodfunction can be used to call an arbitrary method of an object The parameters are the object the name of the method to call a format string like that used withPyBuildValue and the argument valuesPyObjectPyObjectCallMethodPyObjectobjectconstcharmethodnameconstcharargformatThis works for any object that has methods whether builtin or userdefined You are responsible for eventuallyPyDECREFing the return valueTo call eg a file objects seek method with arguments 10 0 assuming the file object pointer is fresPyObjectCallMethodfseekii100ifresNULLanexceptionoccurredelsePyDECREFresNote that sincePyObjectCallObjectalwayswants a tuple for the argument list to call a function without arguments pass for the format and to call a function with one argument surround the argument in parentheses eg i", "Question": "How do i call an object s method from c?"}
{"Answer": "When using GDB with dynamically loaded extensions you cant set a breakpoint in your extension until your extension is loadedIn yourgdbinitfile or interactively add the commandbr PyImportLoadDynamicModuleThen when you run GDBgdblocalbinpythongdb run myscriptpygdb continue repeat until your extension is loadedgdb finish so that your extension is loadedgdb br myfunctionc50gdb continue", "Question": "How do i debug an extension?"}
{"Answer": "Usually Python starts very quickly on Windows but occasionally there are bug reports that Python suddenly begins to take a long time to start up This is made even more puzzling because Python will work fine on other Windows systems which appear to be configured identicallyThe problem may be caused by a misconfiguration of virus checking software on the problem machine Some virus scanners have been known to introduce startup overhead of two orders of magnitude when the scanner is configured to monitor all reads from the filesystem Try checking the configuration of virus scanning software on your systems to ensure that they are indeed configured identically McAfee when configured to scan all file system read activity is a particular offender", "Question": "Why does python sometimes take so long to start?"}
{"Answer": "Embedding the Python interpreter in a Windows app can be summarized as followsDonotbuild Python into your exe file directly On Windows Python must be a DLL to handle importing modules that are themselves DLLs This is the first key undocumented fact Instead link topythonNNdll it is typically installed inCWindowsSystemNNis the Python version a number such as 33 for Python 33You can link to Python in two different ways Loadtime linking means linking againstpythonNNlib while runtime linking means linking againstpythonNNdll General notepythonNNlibis the socalled import lib corresponding topythonNNdll It merely defines symbols for the linkerRuntime linking greatly simplifies link options everything happens at run time Your code must loadpythonNNdllusing the WindowsLoadLibraryExroutine The code must also use access routines and data inpythonNNdllthat is Pythons C APIs using pointers obtained by the WindowsGetProcAddressroutine Macros can make using these pointers transparent to any C code that calls routines in Pythons C APIIf you use SWIG it is easy to create a Python extension module that will make the apps data and methods available to Python SWIG will handle just about all the grungy details for you The result is C code that you linkintoyour exe file You donothave to create a DLL file and this also simplifies linkingSWIG will create an init function a C function whose name depends on the name of the extension module For example if the name of the module is leo the init function will be called initleo If you use SWIG shadow classes as you should the init function will be called initleoc This initializes a mostly hidden helper class used by the shadow classThe reason you can link the C code in step 2 into your exe file is that calling the initialization function is equivalent to importing the module into Python This is the second key undocumented factIn short you can use the following code to initialize the Python interpreter with your extension moduleincludePythonhPyInitialize Initialize PythoninitmyAppc Initialize import the helper classPyRunSimpleStringimport myApp Import the shadow classThere are two problems with Pythons C API which will become apparent if you use a compiler other than MSVC the compiler used to build pythonNNdllProblem 1 The socalled Very High Level functions that takeFILEarguments will not work in a multicompiler environment because each compilers notion of astructFILEwill be different From an implementation standpoint these are very low level functionsProblem 2 SWIG generates the following code when generating wrappers to void functionsPyINCREFPyNoneresultobjPyNonereturnresultobjAlas PyNone is a macro that expands to a reference to a complex data structure called PyNoneStruct inside pythonNNdll Again this code will fail in a multcompiler environment Replace such code byreturnPyBuildValueIt may be possible to use SWIGstypemapcommand to make the change automatically though I have not been able to get this to work Im a complete SWIG newbieUsing a Python shell script to put up a Python interpreter window from inside your Windows app is not a good idea the resulting window will be independent of your apps windowing system Rather you or the wxPythonWindow class should create a native interpreter window It is easy to connect that window to the Python interpreter You can redirect Pythons io to any object that supports read and write so all you need is a Python object defined in your extension module that contains read and write methods", "Question": "How can i embed python into a windows application?"}
{"Answer": "This is not necessarily a straightforward question If you are already familiar with running programs from the Windows command line then everything will seem obvious otherwise you might need a little more guidanceUnless you use some sort of integrated development environment you will end uptypingWindows commands into what is referred to as a Command prompt window Usually you can create such a window from your search bar by searching forcmd You should be able to recognize when you have started such a window because you will see a Windows command prompt which usually looks like thisCThe letter may be different and there might be other things after it so you might just as easily see something likeDYourNameProjectsPythondepending on how your computer has been set up and what else you have recently done with it Once you have started such a window you are well on the way to running Python programsYou need to realize that your Python scripts have to be processed by another program called the Pythoninterpreter The interpreter reads your script compiles it into bytecodes and then executes the bytecodes to run your program So how do you arrange for the interpreter to handle your PythonFirst you need to make sure that your command window recognises the word py as an instruction to start the interpreter If you have opened a command window you should try entering the commandpyand hitting returnCUsersYourNamepyYou should then see something likePython 364 v364d48eceb Dec 19 2017 060445 MSC v1900 32 bit Intel on win32Type help copyright credits or license for more informationYou have started the interpreter in interactive mode That means you can enter Python statements or expressions interactively and have them executed or evaluated while you wait This is one of Pythons strongest features Check it by entering a few expressions of your choice and seeing the resultsprintHelloHelloHello3HelloHelloHelloMany people use the interactive mode as a convenient yet highly programmable calculator When you want to end your interactive Python session call theexitfunction or hold theCtrlkey down while you enter aZ then hit the Enter key to get back to your Windows command promptYou may also find that you have a Startmenu entry such asStart Programs Python 3x Python command linethat results in you seeing theprompt in a new window If so the window will disappear after you call theexitfunction or enter theCtrlZcharacter Windows is running a single python command in the window and closes it when you terminate the interpreterNow that we know thepycommand is recognized you can give your Python script to it Youll have to give either an absolute or a relative path to the Python script Lets say your Python script is located in your desktop and is namedhellopy and your command prompt is nicely opened in your home directory so youre seeing something similar toCUsersYourNameSo now youll ask thepycommand to give your script to Python by typingpyfollowed by your script pathCUsersYourName py Desktophellopy hello", "Question": "How do i run a python program under windows?"}
{"Answer": "SeeHow can I create a standalone binary from a Python scriptfor a list of tools that can be used to make executables", "Question": "How do i make an executable from a python script?"}
{"Answer": "Use themsvcrtmodule This is a standard Windowsspecific extension module It defines a functionkbhitwhich checks whether a keyboard hit is present andgetchwhich gets one character without echoing it", "Question": "How do i check for a keypress without blocking?"}
{"Answer": " occur on Python 35 and later when using Windows 81 or earlier without all updates having been installed First ensure your operating system is supported and is up to date and if that does not resolve the issue visit theMicrosoft support pagefor guidance on manually installing the C Runtime update", "Question": "How do i solve the missing api ms win crt runtime l1 1 0 dll error?"}
{"Answer": "On Windows the standard Python installer already associates the py extension with a file type PythonFile and gives that file type an open command that runs the interpreter DProgramFilesPythonpythonexe1 This is enough to make scripts executable from the command prompt as foopy If youd rather be able to execute the script by simple typing foo with no extension you need to add py to the PATHEXT environment variable", "Question": "How do i make python scripts executable?"}
{"Answer": "The FAQ does not recommend using tabs and the Python style guidePEP 8 recommends 4 spaces for distributed Python code this is also the Emacs pythonmode defaultUnder any editor mixing tabs and spaces is a bad idea MSVC is no different in this respect and is easily configured to use spaces TakeTools Options Tabs and for file type Default set Tab size and Indent size to 4 and select the Insert spaces radio buttonPython raisesIndentationErrororTabErrorif mixed tabs and spaces are causing problems in leading whitespace You may also run thetabnannymodule to check a directory tree in batch mode", "Question": "How do i keep editors from inserting tabs into my python source?"}
{"Answer": "", "Question": "Windows faq?"}
{"Answer": "s pyd files are dlls but there are a few differences If you have a DLL namedfoopyd then it must have a functionPyInitfoo You can then write Python import foo and Python will search for foopyd as well as foopy foopyc and if it finds it will attempt to callPyInitfooto initialize it You do not link your exe with foolib as that would cause Windows to require the DLL to be presentNote that the search path for foopyd is PYTHONPATH not the same as the path that Windows uses to search for foodll Also foopyd need not be present to run your program whereas if you linked your program with a dll the dll is required Of course foopyd is required if you want to sayimportfoo In a DLL linkage is declared in the source code withdeclspecdllexport In a pyd linkage is defined in a list of available functions", "Question": "Is a pyd file the same as a dll?"}