Answer stringlengths 0 5.21k | Question stringlengths 4 109 |
|---|---|
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 floa... | Why are floating point calculations so inaccurate? |
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 ... | How are lists implemented in cpython? |
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 th... | How fast are exceptions? |
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 | Why don t generators support the with statement? |
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 uncomfor... | Why is join a string method instead of a list or tuple method? |
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 examplefunctionsafun... | Why isn t there a switch or case statement in python? |
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 h... | Why does python use indentation for grouping of statements? |
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 t... | How does python manage memory? |
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... | Can t you emulate threads in the interpreter instead of relying on an os specific thread implementation? |
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... | Why must dictionary keys be immutable? |
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 appro... | Why are there separate tuple and list data types? |
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 def... | Why must self be used explicitly in method definitions and calls? |
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 ... | Why isn t all memory freed when cpython exits? |
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 p... | Why can t raw strings r strings end with a backslash? |
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 | Can python be compiled to machine code c or some other language? |
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 ... | Why does python use methods for some functionality e g list index but functions for other e g len list? |
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 fun... | How are dictionaries implemented in cpython? |
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 containingcon... | Why is there no goto? |
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... | How do you specify and enforce an interface spec in python? |
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 sendser... | How do i send mail from a python script? |
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 | Why don t my signal handlers work? |
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 ... | How do i find a module or application to perform task x? |
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 writeusrlocalbinpyth... | How do i make a python script executable on unix? |
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 | How do i create documentation from doc strings? |
For Win32 OSX Linux BSD Jython IronPythonhttpspypiorgprojectpyserialFor Unix see a Usenet post by Mitch Chapmanhttpsgroupsgooglecomgroupsselm34A04430CF9ohioeecom | How do i access the serial rs232 port? |
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 fun... | Is there a curses termcap package for python? |
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 | How do i copy a file? |
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 ... | How do i generate random numbers in python? |
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 implementatio... | What kinds of global value mutation are thread safe? |
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 automatica... | Why doesn t closing sys stdout stdin stderr really close it? |
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 actu... | Can t we get rid of the global interpreter lock? |
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 u... | How do i test a python program or component? |
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... | How do i parcel out work among a bunch of worker threads? |
For Unix variants there are several solutions Its straightforward to do this using curses but curses is a fairly large module to learn | How do i get a single keypress at a time? |
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 existosremovedirspathwi... | How do i delete a file and other file questions? |
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 maintain... | What www tools are there for python? |
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 finishimportthreadingtimedefthreadtasknamenforiinrangenprintnameiforiinrange10Tthrea... | None of my threads seem to run why? |
heatexitmodule provides a register function that is similar to Csonexit | Is there an equivalent to c s onexit in python? |
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 t... | How do i avoid blocking in the connect method of a socket? |
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 | How do you implement persistent objects in python? |
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 i... | Where is the math py socket py regex py etc source file? |
You can find a collection of useful links on theWeb Programming wiki page | What module should i use to help with generating html? |
Be sure to use thethreadingmodule and not thethreadmodule Thethreadingmodule builds convenient abstractions on top of the lowlevel primitives provided by thethreadmodule | How do i program using threads? |
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 pathrequrllibrequesturlop... | How can i mimic cgi form submission method post? |
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 | Are there any interfaces to database packages in python? |
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 | I can t seem to use os read on a pipe created with os popen why? |
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 fileimportstructwith... | How do i read or write binary data? |
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 ... | How do i access a module written in python from c? |
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 | I added a module using the setup file and the make fails why? |
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 inv... | How do i tell incomplete input from invalid input? |
Call the functionPyRunStringfrom the previous question with the start symbolPyevalinput it parses an expression evaluates it and returns its value | How can i evaluate an arbitrary python expression from c? |
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 theioStringIOclassimportiosyssysstdoutioStringIOpri... | How do i catch the output from pyerr print or anything that prints to stdout stderr? |
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... | Writing c is hard are there any alternatives? |
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 byt... | How do i extract c values from a python object? |
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 | How do i find undefined g symbols builtin new or pure virtual? |
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 | Can i create my own functions in c? |
ou cant UsePyTuplePackinstead | How do i use py buildvalue to create a tuple of arbitrary length? |
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 | I want to compile a python module on my linux system but some files are missing why? |
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 | How can i execute arbitrary python statements from c? |
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 | Can i create an object class with some methods implemented in c and others in python e g through inheritance? |
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 | Id1? |
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 w... | How do i interface to c objects from python? |
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 th... | How do i call an object s method from c? |
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... | How do i debug an extension? |
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 misconfiguratio... | Why does python sometimes take so long to start? |
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 inCWindowsSyste... | How can i embed python into a windows application? |
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 wh... | How do i run a python program under windows? |
SeeHow can I create a standalone binary from a Python scriptfor a list of tools that can be used to make executables | How do i make an executable from a python script? |
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 | How do i check for a keypress without blocking? |
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 | How do i solve the missing api ms win crt runtime l1 1 0 dll error? |
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 scr... | How do i make python scripts executable? |
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 f... | How do i keep editors from inserting tabs into my python source? |
Windows faq? | |
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... | Is a pyd file the same as a dll? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.