Skip to main content

Python Language Notes (Overview)

External modules

A listing of frequently used external Python modules (list updated as needed):

ModuleDescription
tbddesc

Standard library modules

A listing of frequently used standard library Python modules (list updated as needed):

ModuleDescription
Data Structures and Algorithms
collectionsContainer datatypes
functoolsHigher-order functions and operations on callable objects
itertoolsFunctions creating iterators for efficient looping
copyShallow and deep copy operations
jsonEncode and decode the JSON format
json.toolA command line to validate and pretty-print JSON
heapqHeap queue algorithm (a.k.a. priority queue)
queueA synchronized queue class
graphlibFunctionality to operate with graph-like structures
reRegular expression operations
stringCommon string operations
cmathMathematical functions for complex numbers
mathMathematical functions (sin() etc.)
randomGenerate pseudo-random numbers with various common distributions
statisticsMathematical statistics functions
Dates and Times
calendarFunctions for working with calendars, including some emulation of the Unix cal program
datetimeBasic date and time types
Debugging and Testing
difflibHelpers for computing differences between objects
inspectExtract information and source code from live objects
loggingFlexible event logging system for applications
pdbThe Python debugger for interactive interpreters
timeTime access and conversions
timeitMeasure the execution time of small code snippets
unittestUnit testing framework for Python
unittest.mockMock object library
warningsIssue warning messages and control their disposition
Documentation
doctestTest pieces of code within docstrings
pydocDocumentation generator and online help system
typesNames for built-in types
typingSupport for type hints (see :pep:484)
Encoding and Decoding
base64RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85
hashlibSecure hash and message digest algorithms
uuidUUID objects (universally unique identifiers) according to RFC 4122
File Manipulation and Input/Output
asyncioAsynchronous I/O
csvWrite and read tabular data to and from delimited files
ioCore tools for working with streams
osMiscellaneous operating system interfaces
pathlibObject-oriented filesystem paths
sysAccess system-specific parameters and functions
sysconfigPython's configuration information
tempfileGenerate temporary files and directories
textwrapText wrapping and filling
Reference
__main__The environment where the top-level script is run
dataclassesGenerate special methods on user-defined classes
emailPackage supporting the parsing, manipulating, and generating email messages
globUnix shell style pathname pattern expansion
keywordTest whether a string is a keyword in Python
venvCreation of virtual environments

Complete standard library module index

ModuleDescription
-
__future__Future statement definitions
__main__The environment where the top-level script is run
_threadLow-level threading API
A
abcAbstract base classes according to :pep:3119
aifcRead and write audio files in AIFF or AIFC format
argparseCommand-line option and argument parsing library
arraySpace efficient arrays of uniformly typed numeric values
astAbstract Syntax Tree classes and manipulation
asynchatSupport for asynchronous command/response protocols
asyncioAsynchronous I/O
asyncoreA base class for developing asynchronous socket handling services
atexitRegister and execute cleanup functions
audioopManipulate raw audio data
B
base64RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85
bdbDebugger framework
binasciiTools for converting between binary and various ASCII-encoded binary representations
binhexEncode and decode files in binhex4 format
bisectArray bisection algorithms for binary searching
builtinsThe module that provides the built-in namespace
bz2Interfaces for bzip2 compression and decompression
C
calendarFunctions for working with calendars, including some emulation of the Unix cal program
cgiHelpers for running Python scripts via the Common Gateway Interface
cgitbConfigurable traceback handler for CGI scripts
chunkModule to read IFF chunks
cmathMathematical functions for complex numbers
cmdBuild line-oriented command interpreters
codeFacilities to implement read-eval-print loops
codecsEncode and decode data and streams
codeopCompile (possibly incomplete) Python code
collectionsContainer datatypes
collections.abcAbstract base classes for containers
colorsysConversion functions between RGB and other color systems
compileallTools for byte-compiling all Python source files in a directory tree
concurrent
concurrent.futuresExecute computations concurrently using threads or processes
configparserConfiguration file parser
contextlibUtilities for with-statement contexts
contextvarsContext Variables
copyShallow and deep copy operations
copyregRegister pickle support functions
cProfile
crypt (Unix)The crypt() function used to check Unix passwords
csvWrite and read tabular data to and from delimited files
ctypesA foreign function library for Python
curses (Unix)An interface to the curses library, providing portable terminal handling
curses.asciiConstants and set-membership functions for ASCII characters
curses.panelA panel stack extension that adds depth to curses windows
curses.textpadEmacs-like input editing in a curses window
D
dataclassesGenerate special methods on user-defined classes
datetimeBasic date and time types
dbmInterfaces to various Unix "database" formats
dbm.dumbPortable implementation of the simple DBM interface
dbm.gnu (Unix)GNU's reinterpretation of dbm
dbm.ndbm (Unix)The standard "database" interface, based on ndbm
decimalImplementation of the General Decimal Arithmetic Specification
difflibHelpers for computing differences between objects
disDisassembler for Python bytecode
distutilsSupport for building and installing Python modules into an existing Python installation
distutils.archive_utilUtility functions for creating archive files (tarballs, zip files, ...)
distutils.bcppcompiler
distutils.ccompilerAbstract CCompiler class
distutils.cmdProvides the abstract base class :class:~distutils.cmd.Command. This class is subclassed by the modules in the distutils.command subpackage.
distutils.commandContains one module for each standard Distutils command
distutils.command.bdistBuild a binary installer for a package
distutils.command.bdist_dumbBuild a "dumb" installer - a simple archive of files
distutils.command.bdist_msiBuild a binary distribution as a Windows MSI file
distutils.command.bdist_packagerAbstract base class for packagers
distutils.command.bdist_rpmBuild a binary distribution as a Redhat RPM and SRPM
distutils.command.bdist_wininstBuild a Windows installer
distutils.command.buildBuild all files of a package
distutils.command.build_clibBuild any C libraries in a package
distutils.command.build_extBuild any extensions in a package
distutils.command.build_pyBuild the .py/.pyc files of a package
distutils.command.build_scriptsBuild the scripts of a package
distutils.command.checkCheck the meta-data of a package
distutils.command.cleanClean a package build area
distutils.command.configPerform package configuration
distutils.command.installInstall a package
distutils.command.install_dataInstall data files from a package
distutils.command.install_headersInstall C/C++ header files from a package
distutils.command.install_libInstall library files from a package
distutils.command.install_scriptsInstall script files from a package
distutils.command.registerRegister a module with the Python Package Index
distutils.command.sdistBuild a source distribution
distutils.coreThe core Distutils functionality
distutils.cygwinccompiler
distutils.debugProvides the debug flag for distutils
distutils.dep_utilUtility functions for simple dependency checking
distutils.dir_utilUtility functions for operating on directories and directory trees
distutils.distProvides the Distribution class, which represents the module distribution being built/installed/distributed
distutils.errorsProvides standard distutils exceptions
distutils.extensionProvides the Extension class, used to describe C/C++ extension modules in setup scripts
distutils.fancy_getoptAdditional getopt functionality
distutils.file_utilUtility functions for operating on single files
distutils.filelistThe FileList class, used for poking about the file system and building lists of files.
distutils.logA simple logging mechanism, :pep:282-style
distutils.msvccompilerMicrosoft Compiler
distutils.spawnProvides the spawn() function
distutils.sysconfigLow-level access to configuration information of the Python interpreter
distutils.text_fileProvides the TextFile class, a simple interface to text files
distutils.unixccompilerUNIX C Compiler
distutils.utilMiscellaneous other utility functions
distutils.versionImplements classes that represent module version numbers
doctestTest pieces of code within docstrings
E
emailPackage supporting the parsing, manipulating, and generating email messages
email.charsetCharacter Sets
email.contentmanagerStoring and Retrieving Content from MIME Parts
email.encodersEncoders for email message payloads
email.errorsThe exception classes used by the email package
email.generatorGenerate flat text email messages from a message structure
email.headerRepresenting non-ASCII headers
email.headerregistryAutomatic Parsing of headers based on the field name
email.iteratorsIterate over a message object tree
email.messageThe base class representing email messages
email.mimeBuild MIME messages
email.parserParse flat text email messages to produce a message object structure
email.policyControlling the parsing and generating of messages
email.utilsMiscellaneous email package utilities
encodings
encodings.idnaInternationalized Domain Names implementation
encodings.mbcsWindows ANSI codepage
encodings.utf_8_sigUTF-8 codec with BOM signature
ensurepipBootstrapping the "pip" installer into an existing Python installation or virtual environment
enumImplementation of an enumeration class
errnoStandard errno system symbols
F
faulthandlerDump the Python traceback
fcntl (Unix)The fcntl() and ioctl() system calls
filecmpCompare files efficiently
fileinputLoop over standard input or a list of files
fnmatchUnix shell style filename pattern matching
formatterDeprecated: Generic output formatter and device interface
fractionsRational numbers
ftplibFTP protocol client (requires sockets)
functoolsHigher-order functions and operations on callable objects
G
gcInterface to the cycle-detecting garbage collector
getoptPortable parser for command line options; support both short and long option names
getpassPortable reading of passwords and retrieval of the userid
gettextMultilingual internationalization services
globUnix shell style pathname pattern expansion
graphlibFunctionality to operate with graph-like structures
grp (Unix)The group database (getgrnam() and friends)
gzipInterfaces for gzip compression and decompression using file objects
H
hashlibSecure hash and message digest algorithms
heapqHeap queue algorithm (a.k.a. priority queue)
hmacKeyed-Hashing for Message Authentication (HMAC) implementation
htmlHelpers for manipulating HTML
html.entitiesDefinitions of HTML general entities
html.parserA simple parser that can handle HTML and XHTML
httpHTTP status codes and messages
http.clientHTTP and HTTPS protocol client (requires sockets)
http.cookiejarClasses for automatic handling of HTTP cookies
http.cookiesSupport for HTTP state management (cookies)
http.serverHTTP server and request handlers
I
imaplibIMAP4 protocol client (requires sockets)
imghdrDetermine the type of image contained in a file or byte stream
impDeprecated: Access the implementation of the import statement
importlibThe implementation of the import machinery
importlib.abcAbstract base classes related to import
importlib.machineryImporters and path hooks
importlib.metadataThe implementation of the importlib metadata
importlib.resourcesPackage resource reading, opening, and access
importlib.utilUtility code for importers
inspectExtract information and source code from live objects
ioCore tools for working with streams
ipaddressIPv4/IPv6 manipulation library
itertoolsFunctions creating iterators for efficient looping
J
jsonEncode and decode the JSON format
json.toolA command line to validate and pretty-print JSON
K
keywordTest whether a string is a keyword in Python
L
lib2to3The 2to3 library
linecacheProvides random access to individual lines from text files
localeInternationalization services
loggingFlexible event logging system for applications
logging.configConfiguration of the logging module
logging.handlersHandlers for the logging module
lzmaA Python wrapper for the liblzma compression library
M
mailboxManipulate mailboxes in various formats
mailcapMailcap file handling
marshalConvert Python objects to streams of bytes and back (with different constraints)
mathMathematical functions (sin() etc.)
mimetypesMapping of filename extensions to MIME types
mmapInterface to memory-mapped files for Unix and Windows
modulefinderFind modules used by a script
msilib (Windows)Creation of Microsoft Installer files, and CAB files
msvcrt (Windows)Miscellaneous useful routines from the MS VC++ runtime
multiprocessingProcess-based parallelism
multiprocessing.connectionAPI for dealing with sockets
multiprocessing.dummyDumb wrapper around threading
multiprocessing.managersShare data between process with shared objects
multiprocessing.poolCreate pools of processes
multiprocessing.shared_memoryProvides shared memory for direct access across processes
multiprocessing.sharedctypesAllocate ctypes objects from shared memory
N
netrcLoading of .netrc files
nis (Unix)Interface to Sun's NIS (Yellow Pages) library
nntplibNNTP protocol client (requires sockets)
numbersNumeric abstract base classes (Complex, Real, Integral, etc.)
O
operatorFunctions corresponding to the standard operators
optparseDeprecated: Command-line option parsing library
osMiscellaneous operating system interfaces
os.pathOperations on pathnames
ossaudiodev(Linux, FreeBSD) Access to OSS-compatible audio devices
P
parserAccess parse trees for Python source code
pathlibObject-oriented filesystem paths
pdbThe Python debugger for interactive interpreters
pickleConvert Python objects to streams of bytes and back
pickletoolsContains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions
pipes (Unix)A Python interface to Unix shell pipelines
pkgutilUtilities for the import system
platformRetrieves as much platform identifying data as possible
plistlibGenerate and parse Apple plist files
poplibPOP3 protocol client (requires sockets)
posix (Unix)The most common POSIX system calls (normally used via module os)
pprintData pretty printer
profilePython source profiler
pstatsStatistics object for use with the profiler
pty (Linux)Pseudo-Terminal Handling for Linux
pwd (Unix)The password database (getpwnam() and friends)
py_compileGenerate byte-code files from Python source files
pyclbrSupports information extraction for a Python module browser
pydocDocumentation generator and online help system
Q
queueA synchronized queue class
quopriEncode and decode files using the MIME quoted-printable encoding
R
randomGenerate pseudo-random numbers with various common distributions
reRegular expression operations
readline (Unix)GNU readline support for Python
reprlibAlternate repr() implementation with size limits
resource (Unix)An interface to provide resource usage information on the current process
rlcompleterPython identifier completion, suitable for the GNU readline library
runpyLocate and run Python modules without importing them first
S
schedGeneral purpose event scheduler
secretsGenerate secure random numbers for managing secrets
selectWait for I/O completion on multiple streams
selectorsHigh-level I/O multiplexing
shelvePython object persistence
shlexSimple lexical analysis for Unix shell-like languages
shutilHigh-level file operations, including copying
signalSet handlers for asynchronous events
siteModule responsible for site-specific configuration
smtpdA SMTP server implementation in Python
smtplibSMTP protocol client (requires sockets)
sndhdrDetermine type of a sound file
socketLow-level networking interface
socketserverA framework for network servers
spwd (Unix)The shadow password database (getspnam() and friends)
sqlite3A DB-API 2.0 implementation using SQLite 3.x
sslTLS/SSL wrapper for socket objects
statUtilities for interpreting the results of os.stat(), os.lstat() and os.fstat()
statisticsMathematical statistics functions
stringCommon string operations
stringprepString preparation, as per RFC 3453
structInterpret bytes as packed binary data
subprocessSubprocess management
sunauProvide an interface to the Sun AU sound format
symbolConstants representing internal nodes of the parse tree
symtableInterface to the compiler's internal symbol tables
sysAccess system-specific parameters and functions
sysconfigPython's configuration information
syslog (Unix)An interface to the Unix syslog library routines
T
tabnannyTool for detecting white space related problems in Python source files in a directory tree
tarfileRead and write tar-format archive files
telnetlibTelnet client class
tempfileGenerate temporary files and directories
termios (Unix)POSIX style tty control
testRegression tests package containing the testing suite for Python
test.supportSupport for Python's regression test suite
test.support.bytecode_helperSupport tools for testing correct bytecode generation
test.support.script_helperSupport for Python's script execution tests
test.support.socket_helperSupport for socket tests
textwrapText wrapping and filling
threadingThread-based parallelism
timeTime access and conversions
timeitMeasure the execution time of small code snippets
tkinterInterface to Tcl/Tk for graphical user interfaces
tkinter.colorchooser (Tk)Color choosing dialog
tkinter.commondialog (Tk)Tkinter base class for dialogs
tkinter.dnd (Tk)Tkinter drag-and-drop interface
tkinter.filedialog (Tk)Dialog classes for file selection
tkinter.font (Tk)Tkinter font-wrapping class
tkinter.messagebox (Tk)Various types of alert dialogs
tkinter.scrolledtext (Tk)Text widget with a vertical scroll bar
tkinter.simpledialog (Tk)Simple dialog windows
tkinter.tixTk Extension Widgets for Tkinter
tkinter.ttkTk themed widget set
tokenConstants representing terminal nodes of the parse tree
tokenizeLexical scanner for Python source code
traceTrace or track Python statement execution
tracebackPrint or retrieve a stack traceback
tracemallocTrace memory allocations
tty (Unix)Utility functions that perform common terminal control operations
turtleAn educational framework for simple graphics applications
turtledemoA viewer for example turtle scripts
typesNames for built-in types
typingSupport for type hints (see :pep:484)
U
unicodedataAccess the Unicode Database
unittestUnit testing framework for Python
unittest.mockMock object library
urllib
urllib.errorException classes raised by urllib.request
urllib.parseParse URLs into or assemble them from components
urllib.requestExtensible library for opening URLs
urllib.responseResponse classes used by urllib
urllib.robotparserLoad a robots.txt file and answer questions about fetchability of other URLs
uuEncode and decode files in uuencode format
uuidUUID objects (universally unique identifiers) according to RFC 4122
V
venvCreation of virtual environments
W
warningsIssue warning messages and control their disposition
waveProvide an interface to the WAV sound format
weakrefSupport for weak references and weak dictionaries
webbrowserEasy-to-use controller for Web browsers
winreg (Windows)Routines and objects for manipulating the Windows registry
winsound (Windows)Access to the sound-playing machinery for Windows
wsgirefWSGI Utilities and Reference Implementation
wsgiref.handlersWSGI server/gateway base classes
wsgiref.headersWSGI response header tools
wsgiref.simple_serverA simple WSGI HTTP server
wsgiref.utilWSGI environment utilities
wsgiref.validateWSGI conformance checker
X
xdrlibEncoders and decoders for the External Data Representation (XDR)
xmlPackage containing XML processing modules
xml.domDocument Object Model API for Python
xml.dom.minidomMinimal Document Object Model (DOM) implementation
xml.dom.pulldomSupport for building partial DOM trees from SAX events
xml.etree.ElementTreeImplementation of the ElementTree API
xml.parsers.expatAn interface to the Expat non-validating XML parser
xml.parsers.expat.errors
xml.parsers.expat.model
xml.saxPackage containing SAX2 base classes and convenience functions
xml.sax.handlerBase classes for SAX event handlers
xml.sax.saxutilsConvenience functions and classes for use with SAX
xml.sax.xmlreaderInterface which SAX-compliant XML parsers must implement
xmlrpc
xmlrpc.clientXML-RPC client access
xmlrpc.serverBasic XML-RPC server implementations
Z
zipappManage executable Python zip archives
zipfileRead and write ZIP-format archive files
zipimportSupport for importing Python modules from ZIP archives
zlibLow-level interface to compression and decompression routines compatible with gzip
zoneinfoIANA time zone support

Built-in functions

FunctionDescription
abs()Returns the absolute value of a number
all()Returns True if all items in an iterable object are true
any()Returns True if any item in an iterable object is true
ascii()Returns a readable version of an object. Replaces none-ascii characters with escape character
bin()Returns the binary version of a number
bool()Returns the boolean value of the specified object
bytearray()Returns an array of bytes
bytes()Returns a bytes object
callable()Returns True if the specified object is callable, otherwise False
chr()Returns a character from the specified Unicode code.
classmethod()Converts a method into a class method
compile()Returns the specified source as an object, ready to be executed
complex()Returns a complex number
delattr()Deletes the specified attribute (property or method) from the specified object
dict()Returns a dictionary (Array)
dir()Returns a list of the specified object's properties and methods
divmod()Returns the quotient and the remainder when argument1 is divided by argument2
enumerate()Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval()Evaluates and executes an expression
exec()Executes the specified code (or object)
filter()Use a filter function to exclude items in an iterable object
float()Returns a floating point number
format()Formats a specified value
frozenset()Returns a frozenset object
getattr()Returns the value of the specified attribute (property or method)
globals()Returns the current global symbol table as a dictionary
hasattr()Returns True if the specified object has the specified attribute (property/method)
hash()Returns the hash value of a specified object
help()Executes the built-in help system
hex()Converts a number into a hexadecimal value
id()Returns the id of an object
input()Allowing user input
int()Returns an integer number
isinstance()Returns True if a specified object is an instance of a specified object
issubclass()Returns True if a specified class is a subclass of a specified object
iter()Returns an iterator object
len()Returns the length of an object
list()Returns a list
locals()Returns an updated dictionary of the current local symbol table
map()Returns the specified iterator with the specified function applied to each item
max()Returns the largest item in an iterable
memoryview()Returns a memory view object
min()Returns the smallest item in an iterable
next()Returns the next item in an iterable
object()Returns a new object
oct()Converts a number into an octal
open()Opens a file and returns a file object
ord()Convert an integer representing the Unicode of the specified character
pow()Returns the value of x to the power of y
print()Prints to the standard output device
property()Gets, sets, deletes a property
range()Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr()Returns a readable version of an object
reversed()Returns a reversed iterator
round()Rounds a numbers
set()Returns a new set object
setattr()Sets an attribute (property/method) of an object
slice()Returns a slice object
sorted()Returns a sorted list
@staticmethod()Converts a method into a static method
str()Returns a string object
sum()Sums the items of an iterator
super()Returns an object that represents the parent class
tuple()Returns a tuple
type()Returns the type of an object
vars()Returns the dict property of an object
zip()Returns an iterator, from two or more iterators

String methods

MethodDescription
capitalize()Converts the first character to upper case
casefold()Converts string into lower case
center()Returns a centered string
count()Returns the number of times a specified value occurs in a string
encode()Returns an encoded version of the string
endswith()Returns true if the string ends with the specified value
expandtabs()Sets the tab size of the string
find()Searches the string for a specified value and returns the position of where it was found
format()Formats specified values in a string
format_map()Formats specified values in a string
index()Searches the string for a specified value and returns the position of where it was found
isalnum()Returns True if all characters in the string are alphanumeric
isalpha()Returns True if all characters in the string are in the alphabet
isdecimal()Returns True if all characters in the string are decimals
isdigit()Returns True if all characters in the string are digits
isidentifier()Returns True if the string is an identifier
islower()Returns True if all characters in the string are lower case
isnumeric()Returns True if all characters in the string are numeric
isprintable()Returns True if all characters in the string are printable
isspace()Returns True if all characters in the string are whitespaces
istitle()Returns True if the string follows the rules of a title
isupper()Returns True if all characters in the string are upper case
join()Joins the elements of an iterable to the end of the string
ljust()Returns a left justified version of the string
lower()Converts a string into lower case
lstrip()Returns a left trim version of the string
maketrans()Returns a translation table to be used in translations
partition()Returns a tuple where the string is parted into three parts
replace()Returns a string where a specified value is replaced with a specified value
rfind()Searches the string for a specified value and returns the last position of where it was found
rindex()Searches the string for a specified value and returns the last position of where it was found
rjust()Returns a right justified version of the string
rpartition()Returns a tuple where the string is parted into three parts
rsplit()Splits the string at the specified separator, and returns a list
rstrip()Returns a right trim version of the string
split()Splits the string at the specified separator, and returns a list
splitlines()Splits the string at line breaks and returns a list
startswith()Returns true if the string starts with the specified value
strip()Returns a trimmed version of the string
swapcase()Swaps cases, lower case becomes upper case and vice versa
title()Converts the first character of each word to upper case
translate()Returns a translated string
upper()Converts a string into upper case
zfill()Fills the string with a specified number of 0 values at the beginning

List methods

MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the first item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list

Dictionary methods

MethodDescription
clear()Removes all the elements from the dictionary
copy()Returns a copy of the dictionary
fromkeys()Returns a dictionary with the specified keys and value
get()Returns the value of the specified key
items()Returns a list containing a tuple for each key value pair
keys()Returns a list containing the dictionary's keys
pop()Removes the element with the specified key
popitem()Removes the last inserted key-value pair
setdefault()Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update()Updates the dictionary with the specified key-value pairs
values()Returns a list of all the values in the dictionary

Tuple methods

MethodDescription
count()Returns the number of times a specified value occurs in a tuple
index()Searches the tuple for a specified value and returns the position of where it was found

Set methods

MethodDescription
add()Adds an element to the set
clear()Removes all the elements from the set
copy()Returns a copy of the set
difference()Returns a set containing the difference between two or more sets
difference_update()Removes the items in this set that are also included in another, specified set
discard()Remove the specified item
intersection()Returns a set, that is the intersection of two other sets
intersection_update()Removes the items in this set that are not present in other, specified set(s)
isdisjoint()Returns whether two sets have a intersection or not
issubset()Returns whether another set contains this set or not
issuperset()Returns whether this set contains another set or not
pop()Removes an element from the set
remove()Removes the specified element
symmetric_difference()Returns a set with the symmetric differences of two sets
symmetric_difference_update()inserts the symmetric differences from this set and another
union()Return a set containing the union of sets
update()Update the set with another set, or any other iterable

File methods

MethodDescription
close()Closes the file
detach()Returns the separated raw stream from the buffer
fileno()Returns a number that represents the stream, from the operating system's perspective
flush()Flushes the internal buffer
isatty()Returns whether the file stream is interactive or not
read()Returns the file content
readable()Returns whether the file stream can be read or not
readline()Returns one line from the file
readlines()Returns a list of lines from the file
seek()Change the file position
seekable()Returns whether the file allows us to change the file position
tell()Returns the current file position
truncate()Resizes the file to a specified size
writable()Returns whether the file can be written to or not
write()Writes the specified string to the file
writelines()Writes a list of strings to the file

Keywords

KeywordDescription
andA logical operator
asTo create an alias
assertFor debugging
breakTo break out of a loop
classTo define a class
continueTo continue to the next iteration of a loop
defTo define a function
delTo delete an object
elifUsed in conditional statements, same as else if
elseUsed in conditional statements
exceptUsed with exceptions, what to do when an exception occurs
FalseBoolean value, result of comparison operations
finallyUsed with exceptions, a block of code that will be executed no matter if there is an exception or not
forTo create a for loop
fromTo import specific parts of a module
globalTo declare a global variable
ifTo make a conditional statement
importTo import a module
inTo check if a value is present in a list, tuple, etc.
isTo test if two variables are equal
lambdaTo create an anonymous function
NoneRepresents a null value
nonlocalTo declare a non-local variable
notA logical operator
orA logical operator
passA null statement, a statement that will do nothing
raiseTo raise an exception
returnTo exit a function and return a value
TrueBoolean value, result of comparison operations
tryTo make a try...except statement
whileTo create a while loop
withUsed to simplify exception handling
yieldTo end a function, returns a generator

Exceptions

ExceptionDescription
ArithmeticErrorRaised when an error occurs in numeric calculations
AssertionErrorRaised when an assert statement fails
AttributeErrorRaised when attribute reference or assignment fails
ExceptionBase class for all exceptions
EOFErrorRaised when the input() method hits an "end of file" condition (EOF)
FloatingPointErrorRaised when a floating point calculation fails
GeneratorExitRaised when a generator is closed (with the close() method)
ImportErrorRaised when an imported module does not exist
IndentationErrorRaised when indendation is not correct
IndexErrorRaised when an index of a sequence does not exist
KeyErrorRaised when a key does not exist in a dictionary
KeyboardInterruptRaised when the user presses Ctrl+c, Ctrl+z or Delete
LookupErrorRaised when errors raised cant be found
MemoryErrorRaised when a program runs out of memory
NameErrorRaised when a variable does not exist
NotImplementedErrorRaised when an abstract method requires an inherited class to override the method
OSErrorRaised when a system related operation causes an error
OverflowErrorRaised when the result of a numeric calculation is too large
ReferenceErrorRaised when a weak reference object does not exist
RuntimeErrorRaised when an error occurs that do not belong to any specific expections
StopIterationRaised when the next() method of an iterator has no further values
SyntaxErrorRaised when a syntax error occurs
TabErrorRaised when indentation consists of tabs or spaces
SystemErrorRaised when a system error occurs
SystemExitRaised when the sys.exit() function is called
TypeErrorRaised when two different types are combined
UnboundLocalErrorRaised when a local variable is referenced before assignment
UnicodeErrorRaised when a unicode problem occurs
UnicodeEncodeErrorRaised when a unicode encoding problem occurs
UnicodeDecodeErrorRaised when a unicode decoding problem occurs
UnicodeTranslateErrorRaised when a unicode translation problem occurs
ValueErrorRaised when there is a wrong value in a specified data type
ZeroDivisionErrorRaised when the second operator in a division is zero

Glossary

FeatureDescription
IndentationIndentation refers to the spaces at the beginning of a code line
CommentsComments are code lines that will not be executed
Multi Line CommentsHow to insert comments on multiple lines
Creating VariablesVariables are containers for storing data values
Variable NamesHow to name your variables
Assign Values to Multiple VariablesHow to assign values to multiple variables
Output VariablesUse the print statement to output variables
String ConcatenationHow to combine strings
Global VariablesGlobal variables are variables that belongs to the global scope
Built-In Data TypesPython has a set of built-in data types
Getting Data TypeHow to get the data type of an object
Setting Data TypeHow to set the data type of an object
NumbersThere are three numeric types in Python
IntThe integer number type
FloatThe floating number type
ComplexThe complex number type
Type ConversionHow to convert from one number type to another
Random NumberHow to create a random number
Specify a Variable TypeHow to specify a certain data type for a variable
String LiteralsHow to create string literals
Assigning a String to a VariableHow to assign a string value to a variable
Multiline StringsHow to create a multi line string
Strings are ArraysStrings in Python are arrays of bytes representing Unicode characters
Slicing a StringHow to slice a string
Negative Indexing on a StringHow to use negative indexing when accessing a string
String LengthHow to get the length of a string
Check In StringHow to check if a string contains a specified phrase
Format StringHow to combine two strings
Escape CharactersHow to use escape characters
Boolean ValuesTrue or False
Evaluate BooleansEvaluate a value or statement and return either True or False
Return Boolean ValueFunctions that return a Boolean value
OperatorsUse operator to perform operations in Python
Arithmetic OperatorsArithmetic operator are used to perform common mathematical operations
Assignment OperatorsAssignment operators are use to assign values to variables
Comparison OperatorsComparison operators are used to compare two values
Logical OperatorsLogical operators are used to combine conditional statements
Identity OperatorsIdentity operators are used to see if two objects are in fact the same object
Membership OperatorsMembership operators are used to test is a sequence is present in an object
Bitwise OperatorsBitwise operators are used to compare (binary) numbers
ListsA list is an ordered, and changeable, collection
Access List ItemsHow to access items in a list
Change List ItemHow to change the value of a list item
Loop Through List ItemsHow to loop through the items in a list
List ComprehensionHow use a list comprehensive
Check if List Item ExistsHow to check if a specified item is present in a list
List LengthHow to determine the length of a list
Add List ItemsHow to add items to a list
Remove List ItemsHow to remove list items
Copy a ListHow to copy a list
Join Two ListsHow to join two lists
TupleA tuple is an ordered, and unchangeable, collection
Access Tuple ItemsHow to access items in a tuple
Change Tuple ItemHow to change the value of a tuple item
Loop List ItemsHow to loop through the items in a tuple
Check if Tuple Item ExistsHow to check if a specified item is present in a tuple
Tuple LengthHow to determine the length of a tuple
Tuple With One ItemHow to create a tuple with only one item
Remove Tuple ItemsHow to remove tuple items
Join Two TuplesHow to join two tuples
SetA set is an unordered, and unchangeable, collection
Access Set ItemsHow to access items in a set
Add Set ItemsHow to add items to a set
Loop Set ItemsDETTE KAPITTELET MANGLER
Check if Set Item ExistsDETTE KAPITTELET MANGLER
Set LengthHow to determine the length of a set
Remove Set ItemsHow to remove set items
Join Two SetsHow to join two sets
DictionaryA dictionary is an unordered, and changeable, collection
Access Dictionary ItemsHow to access items in a dictionary
Change Dictionary ItemHow to change the value of a dictionary item
Loop Dictionary ItemsHow to loop through the items in a tuple
Check if Dictionary Item ExistsHow to check if a specified item is present in a dictionary
Dictionary LengthHow to determine the length of a dictionary
Add Dictionary ItemHow to add an item to a dictionary
Remove Dictionary ItemsHow to remove dictionary items
Copy DictionaryHow to copy a dictionary
Nested DictionariesA dictionary within a dictionary
If StatementHow to write an if statement
If IndentationIf statemnts in Python relies on indentation (whitespace at the beginning of a line)
Elifelif is the same as "else if" in other programming languages
ElseHow to write an if...else statement
Shorthand IfHow to write an if statement in one line
Shorthand If ElseHow to write an if...else statement in one line
If ANDUse the and keyword to combine if statements
If ORUse the or keyword to combine if statements
Nested IfHow to write an if statement inside an if statement
The pass Keyword in IfUse the pass keyword inside empty if statements
WhileHow to write a while loop
While BreakHow to break a while loop
While ContinueHow to stop the current iteration and continue wit the next
While ElseHow to use an else statement in a while loop
ForHow to write a for loop
Loop Through a StringHow to loop through a string
For BreakHow to break a for loop
For ContinueHow to stop the current iteration and continue wit the next
Looping Through a rangeeHow to loop through a range of values
For ElseHow to use an else statement in a for loop
Nested LoopsHow to write a loop inside a loop
For passUse the pass keyword inside empty for loops
FunctionHow to create a function in Python
Call a FunctionHow to call a function in Python
Function ArgumentsHow to use arguments in a function
*argsTo deal with an unknown number of arguments in a function, use the * symbol before the parameter name
Keyword ArgumentsHow to use keyword arguments in a function
*kwargsTo deal with an unknown number of keyword arguments in a function, use the * symbol before the parameter name
Default Parameter ValueHow to use a default parameter value
Passing a List as an ArgumentHow to pass a list as an argument
Function Return ValueHow to return a value from a function
The pass Statement i FunctionsUse the pass statement in empty functions
Function RecursionFunctions that can call itself is called recursive functions
Lambda FunctionHow to create anonymous functions in Python
Why Use Lambda FunctionsLearn when to use a lambda function or not
ArrayLists can be used as Arrays
What is an ArrayArrays are variables that can hold more than one value
Access ArraysHow to access array items
Array LengthHow to get the length of an array
Looping Array ElementsHow to loop through array elements
Add Array ElementHow to add elements from an array
Remove Array ElementHow to remove elements from an array
Array MethodsPython has a set of Array/Lists methods
ClassA class is like an object constructor
Create ClassHow to create a class
The Class init() FunctionThe init() function is executed when the class is initiated
Object MethodsMethods in objects are functions that belongs to the object
selfThe self parameter refers to the current instance of the class
Modify Object PropertiesHow to modify properties of an object
Delete Object PropertiesHow to modify properties of an object
Delete ObjectHow to delete an object
Class pass StatementUse the pass statement in empty classes
Create Parent ClassHow to create a parent class
Create Child ClassHow to create a child class
Create the init() FunctionHow to create the init() function
super FunctionThe super() function make the child class inherit the parent class
Add Class PropertiesHow to add a property to a class
Add Class MethodsHow to add a method to a class
IteratorsAn iterator is an object that contains a countable number of values
Iterator vs IterableWhat is the difference between an iterator and an iterable
Loop Through an IteratorHow to loop through the elements of an iterator
Create an IteratorHow to create an iterator
StopIterationHow to stop an iterator
Global ScopeWhen does a variable belong to the global scope?
Global KeywordThe global keyword makes the variable global
Create a ModuleHow to create a module
Variables in ModulesHow to use variables in a module
Renaming a ModuleHow to rename a module
Built-in ModulesHow to import built-in modules
Using the dir() FunctionList all variable names and function names in a module
Import From ModuleHow to import only parts from a module
Datetime ModuleHow to work with dates in Python
Date OutputHow to output a date
Create a Date ObjectHow to create a date object
The strftime MethodHow to format a date object into a readable string
Date Format CodesThe datetime module has a set of legal format codes
JSONHow to work with JSON in Python
Parse JSONHow to parse JSON code in Python
Convert into JSONHow to convert a Python object in to JSON
Format JSONHow to format JSON output with indentations and line breaks
Sort JSONHow to sort JSON
RegEx ModuleHow to import the regex module
RegEx FunctionsThe re module has a set of functions
Metacharacters in RegExMetacharacters are characters with a special meaning
RegEx Special SequencesA backslash followed by a a character has a special meaning
RegEx SetsA set is a set of characters inside a pair of square brackets with a special meaning
RegEx Match ObjectThe Match Object is an object containing information about the search and the result
Install PIPHow to install PIP
PIP PackagesHow to download and install a package with PIP
PIP Remove PackageHow to remove a package with PIP
Error HandlingHow to handle errors in Python
Handle Many ExceptionsHow to handle more than one exception
Try ElseHow to use the else keyword in a try statement
Try FinallyHow to use the finally keyword in a try statement
raiseHow to raise an exception in Python

W3 School Python module reference with descriptions

Random module

MethodDescription
seed()Initialize the random number generator
getstate()Returns the current internal state of the random number generator
setstate()Restores the internal state of the random number generator
getrandbits()Returns a number representing the random bits
randrange()Returns a random number between the given range
randint()Returns a random number between the given range
choice()Returns a random element from the given sequence
choices()Returns a list with a random selection from the given sequence
shuffle()Takes a sequence and returns the sequence in a random order
sample()Returns a given sample of a sequence
random()Returns a random float number between 0 and 1
uniform()Returns a random float number between two given parameters
triangular()Returns a random float number between two given parameters, you can also set a mode parameter to specify the midpoint between the two other parameters
betavariate()Returns a random float number between 0 and 1 based on the Beta distribution (used in statistics)
expovariate()Returns a random float number based on the Exponential distribution (used in statistics)
gammavariate()Returns a random float number based on the Gamma distribution (used in statistics)
gauss()Returns a random float number based on the Gaussian distribution (used in probability theories)
lognormvariate()Returns a random float number based on a log-normal distribution (used in probability theories)
normalvariate()Returns a random float number based on the normal distribution (used in probability theories)
vonmisesvariate()Returns a random float number based on the von Mises distribution (used in directional statistics)
paretovariate()Returns a random float number based on the Pareto distribution (used in probability theories)
weibullvariate()Returns a random float number based on the Weibull distribution (used in statistics)

Requests module

MethodDescription
delete(url, args)Sends a DELETE request to the specified url
get(url, params, args)Sends a GET request to the specified url
head(url, args)Sends a HEAD request to the specified url
patch(url, data, args)Sends a PATCH request to the specified url
post(url, data, json, args)Sends a POST request to the specified url
put(url, data, args)Sends a PUT request to the specified url
request(method, url, args)Sends a request of the specified method to the specified url

Statistics module

MethodDescription
statistics.harmonic_mean()Calculates the harmonic mean (central location) of the given data
statistics.mean()Calculates the mean (average) of the given data
statistics.median()Calculates the median (middle value) of the given data
statistics.median_grouped()Calculates the median of grouped continuous data
statistics.median_high()Calculates the high median of the given data
statistics.median_low()Calculates the low median of the given data
statistics.mode()Calculates the mode (central tendency) of the given numeric or nominal data
statistics.pstdev()Calculates the standard deviation from an entire population
statistics.stdev()Calculates the standard deviation from a sample of data
statistics.pvariance()Calculates the variance of an entire population
statistics.variance()Calculates the variance from a sample of data

Math module

MethodDescription
math.acos()Returns the arc cosine of a number
math.acosh()Returns the inverse hyperbolic cosine of a number
math.asin()Returns the arc sine of a number
math.asinh()Returns the inverse hyperbolic sine of a number
math.atan()Returns the arc tangent of a number in radians
math.atan2()Returns the arc tangent of y/x in radians
math.atanh()Returns the inverse hyperbolic tangent of a number
math.ceil()Rounds a number up to the nearest integer
math.comb()Returns the number of ways to choose k items from n items without repetition and order
math.copysign()Returns a float consisting of the value of the first parameter and the sign of the second parameter
math.cos()Returns the cosine of a number
math.cosh()Returns the hyperbolic cosine of a number
math.degrees()Converts an angle from radians to degrees
math.dist()Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point
math.erf()Returns the error function of a number
math.erfc()Returns the complementary error function of a number
math.exp()Returns E raised to the power of x
math.expm1()Returns Ex - 1
math.fabs()Returns the absolute value of a number
math.factorial()Returns the factorial of a number
math.floor()Rounds a number down to the nearest integer
math.fmod()Returns the remainder of x/y
math.frexp()Returns the mantissa and the exponent, of a specified number
math.fsum()Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
math.gamma()Returns the gamma function at x
math.gcd()Returns the greatest common divisor of two integers
math.hypot()Returns the Euclidean norm
math.isclose()Checks whether two values are close to each other, or not
math.isfinite()Checks whether a number is finite or not
math.isinf()Checks whether a number is infinite or not
math.isnan()Checks whether a value is NaN (not a number) or not
math.isqrt()Rounds a square root number downwards to the nearest integer
math.ldexp()Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x and i
math.lgamma()Returns the log gamma value of x
math.log()Returns the natural logarithm of a number, or the logarithm of number to base
math.log10()Returns the base-10 logarithm of x
math.log1p()Returns the natural logarithm of 1+x
math.log2()Returns the base-2 logarithm of x
math.perm()Returns the number of ways to choose k items from n items with order and without repetition
math.pow()Returns the value of x to the power of y
math.prod()Returns the product of all the elements in an iterable
math.radians()Converts a degree value into radians
math.remainder()Returns the closest value that can make numerator completely divisible by the denominator
math.sin()Returns the sine of a number
math.sinh()Returns the hyperbolic sine of a number
math.sqrt()Returns the square root of a number
math.tan()Returns the tangent of a number
math.tanh()Returns the hyperbolic tangent of a number
math.trunc()Returns the truncated integer parts of a number
math.eReturns Euler's number (2.7182...)
math.infReturns a floating-point positive infinity
math.nanReturns a floating-point NaN (Not a Number) value
math.piReturns PI (3.1415...)
math.tauReturns tau (6.2831...)

cMath module

MethodDescription
cmath.acos(x)Returns the arc cosine value of x
cmath.acosh(x)Returns the hyperbolic arc cosine of x
cmath.asin(x)Returns the arc sine of x
cmath.asinh(x)Returns the hyperbolic arc sine of x
cmath.atan(x)Returns the arc tangent value of x
cmath.atanh(x)Returns the hyperbolic arctangent value of x
cmath.cos(x)Returns the cosine of x
cmath.cosh(x)Returns the hyperbolic cosine of x
cmath.exp(x)Returns the value of Ex, where E is Euler's number (approximately 2.718281...), and x is the number passed to it
cmath.isclose()Checks whether two values are close, or not
cmath.isfinite(x)Checks whether x is a finite number
cmath.isinf(x)Check whether x is a positive or negative infinty
cmath.isnan(x)Checks whether x is NaN (not a number)
cmath.log(x[, base])Returns the logarithm of x to the base
cmath.log10(x)Returns the base-10 logarithm of x
cmath.phase()Return the phase of a complex number
cmath.polar()Convert a complex number to polar coordinates
cmath.rect()Convert polar coordinates to rectangular form
cmath.sin(x)Returns the sine of x
cmath.sinh(x)Returns the hyperbolic sine of x
cmath.sqrt(x)Returns the square root of x
cmath.tan(x)Returns the tangent of x
cmath.tanh(x)Returns the hyperbolic tangent of x
cmath.eReturns Euler's number (2.7182...)
cmath.infReturns a floating-point positive infinity value
cmath.infjReturns a complex infinity value
cmath.nanReturns floating-point NaN (Not a Number) value
cmath.nanjReturns coplext NaN (Not a Number) value
cmath.piReturns PI (3.1415...)
cmath.tauReturns tau (6.2831...)

Common sequence operations (sequence types: list, tuple, range)

The operations in the following table are supported by most sequence types, both mutable and immutable. The collections.abc.Sequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.

This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s.

The in and not in operations have the same priorities as the comparison operations. The + (concatenation) and * (repetition) operations have the same priority as the corresponding numeric operations.

OperationResultNotes
x in sTrue if an item of s is equal to x, else False(1)
x not in sFalse if an item of s is equal to x, else True(1)
s + tthe concatenation of s and t(6)(7)
s * n or n * sequivalent to adding s to itself n times(2)(7)
s[i]ith item of s, origin 0(3)
s[i:j]slice of s from i to j(3)(4)
s[i:j:k]slice of s from i to j with step k(3)(5))
len(s)length of s
min(s)smallest item of s
max(s)largest item of s
s.index(x[, i[, j]])index of the first occurrence of x in s (at or after index i and before index j)(8)
s.count(x)total number of occurrences of x in s

Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.)

Notes:

1. While the in and not in operations are used only for simple containment testing in the general case, some specialised sequences (such as str, bytes and bytearray) also use them for subsequence testing:

>>> "gg" in "eggs"
True

2. Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:

>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are references to this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

Further explanation is available in the FAQ entry How do I create a multidimensional list?.

3. If i or j is negative, the index is relative to the end of sequence s: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

4. The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

5. The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. If i or j are omitted or None, they become "end" values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

6. Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:

  • if concatenating str objects, you can build a list and use str.join() at the end or else write to an io.StringIO instance and retrieve its value when complete
  • if concatenating bytes objects, you can similarly use bytes.join() or io.BytesIO, or you can do in-place concatenation with a bytearray object. bytearray objects are mutable and have an efficient overallocation mechanism
  • if concatenating tuple objects, extend a list instead
  • for other types, investigate the relevant class documentation

7. Some sequence types (such as range) only support item sequences that follow specific patterns, and hence don't support sequence concatenation or repetition.

8. index raises ValueError when x is not found in s. Not all implementations support passing the additional arguments i and j. These arguments allow efficient searching of subsections of the sequence. Passing the extra arguments is roughly equivalent to using s[i:j].index(x), only without copying any data and with the returned index being relative to the start of the sequence rather than the start of the slice.

Mutable sequence types (operations such as slicing, insert, etc.)

The operations in the following table are defined on mutable sequence types. The collections.abc.MutableSequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.

In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, bytearray only accepts integers that meet the value restriction 0 <= x <= 255).

OperationResultNotes
s[i] = xitem i of s is replaced by x
s[i:j] = tslice of s from i to j is replaced by the contents of the iterable t
del s[i:j]same as s[i:j] = []
s[i:j:k] = tthe elements of s[i:j:k] are replaced by those of t(1)
del s[i:j:k]removes the elements of s[i:j:k] from the list
s.append(x)appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear()removes all items from s (same as del s[:])(5)
s.copy()creates a shallow copy of s (same as s[:])(5)
s.extend(t) or s += textends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)
s *= nupdates s with its contents repeated n times(6)
s.insert(i, x)inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop([i])retrieves the item at i and also removes it from s(2)
s.remove(x)remove the first item from s where s[i] is equal to x(3)
s.reverse()reverses the items of s in place(4)

1. t must have the same length as the slice it is replacing.

2. The optional argument i defaults to -1, so that by default the last item is removed and returned.

3. remove() raises ValueError when x is not found in s.

4. The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence.

5. clear() and copy() are included for consistency with the interfaces of mutable containers that don't support slicing operations (such as dict and set). copy() is not part of the collections.abc.MutableSequence ABC, but most concrete mutable sequence classes provide it.

6. The value n is an integer, or an object implementing __index__(). Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for s * n under Common Sequence Operations.

Docs and Examples

Built-in Functions

abs(x)

Description: The abs() function returns the absolute value of the given number. If the number is a complex number, then abs() returns its magnitude.

Syntax: The syntax of abs() method is: abs(num).

Paramaters: abs() method takes a single argument, num: a number whose absolute value is to be returned. The number can be:

  • integer
  • floating number
  • complex number

Return value: abs() method returns the absolute value of the given number.

  • For integers - integer absolute value is returned
  • For floating numbers - floating absolute value is returned
  • For complex numbers - magnitude of the number is returned

Examples:

Ex 0: Documentation

Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing __abs__(). If the argument is a complex number, its magnitude is returned.


Ex 1: Getting absolute value of an integer and a floating number
# random integer
integer = -20
print('Absolute value of -20 is:', abs(integer))

#random floating number
floating = -30.33
print('Absolute value of -30.33 is:', abs(floating))

Output:

Absolute value of -20 is: 20
Absolute value of -30.33 is: 30.33

Ex 2: Getting magnitude of a complex number
# random complex number
complex = (3 - 4j)
print('Magnitude of 3 - 4j is:', abs(complex))

Output:

Magnitude of 3 - 4j is: 5.0

Ex 3: Example using abs on an int, float, and complex number, respectively
a = -2
b = -3.4
c = complex(-3,-4)

print(abs(a)) # 2
print(abs(b)) # 3.4
print(abs(c)) # 5.0 (comes from: sqrt((-3)^2 + (-4)^2))

As can be seen above, abs returns an int when it receives a whole number and a float otherwise.



aiter(async_iterable)

Return an asynchronous iterator for an asynchronous iterable. Equivalent to calling x.__aiter__().

aiter(x) itself has an __aiter__() method that returns x, so aiter(aiter(x)) is the same as aiter(x).

Note: Unlike iter(), aiter() has no 2-argument variant.

New in version 3.10.


all(iterable)

Description: The all() function returns True if all elements in the given iterable are true (or if the iterable is empty). If not, it returns False.

Syntax: The syntax of the all() function is: all(iterable).

Parameters: The all() function takes a single parameter, iterable: any iterable (list, tuple, dictionary, etc.) which contains elements.

Return value: The all() function returns:

  • True - If all elements in an iterable are true (or if the iterable is empty)
  • False - If any element in an iterable is false

Falsy values in Python: Recall that all values in Python are considered truthy except for the following which are falsy (more can be found in the docs on truth value testing):

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] - an empty list
  • {} - an empty dict
  • () - an empty tuple
  • '' - an empty str
  • b'' - an empty bytes
  • set() - an empty set
  • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0

Examples:

Ex 0: Documentation

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable):
for element in iterable:
if not element:
return False
return True

Ex 1: Lists (works in a similar way for tuples and sets)
# all values true
l = [1, 3, 4, 5]
print(all(l)) # True

# all values false
l = [0, False]
print(all(l)) # False

# one false value
l = [1, 3, 4, 0]
print(all(l)) # False

# one true value
l = [0, False, 5]
print(all(l)) # False

# empty iterable
l = []
print(all(l)) # True

Ex 2: Strings
s = "This is good"
print(all(s)) # True

# 0 is False
# '0' is True
s = '000'
print(all(s)) # True

s = ''
print(all(s)) # True

Some things to note about two of the code examples above:

  • "This is good": This is true because all values (i.e., characters) in the iterable "This is good" are truthy; in particular, the spaces ' ' have an ordinal value of 32 (i.e., ord(' ') returns 32).

  • '': This is true because the iterable '' is empty. Hence, when the functional equivalent of all()

    def all(iterable):
    for element in iterable:
    if not element:
    return False
    return True

    is executed, the for loop never runs and True is quickly returned.


Ex 3: Dictionaries (return True if all keys, not values, are true or the dictionary is empty; else return False)
s = {0: 'False', 1: 'False'}
print(all(s)) # False

s = {1: 'True', 2: 'True'}
print(all(s)) # True

s = {1: 'True', False: 0}
print(all(s)) # False

s = {}
print(all(s)) # True

# 0 is False
# '0' is True
s = {'0': 'True'}
print(all(s)) # True


anext(async_iterator[, default])

When awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted.

This is the async variant of the next() builtin, and behaves similarly.

This calls the __anext__() method of async_iterator, returning an awaitable. Awaiting this returns the next value of the iterator. If default is given, it is returned if the iterator is exhausted, otherwise StopAsyncIteration is raised.

New in version 3.10.


any(iterable)

Description: The any() function returns True if any element of the given iterable is True. If not (or if the iterable is empty), it returns False.

Syntax: The syntax of the any() function is: any(iterable).

Parameters: The any() function takes a single parameter, iterable: any iterable (list, tuple, dictionary, etc.) which contains elements.

Return value: The any() function returns:

  • True - If at least one element of an iterable is true
  • False - If all elements are false or if an iterable is empty

Falsy values in Python: Recall that all values in Python are considered truthy except for the following which are falsy (more can be found in the docs on truth value testing):

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] - an empty list
  • {} - an empty dict
  • () - an empty tuple
  • '' - an empty str
  • b'' - an empty bytes
  • set() - an empty set
  • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0

Examples:

Ex 0: Documentation

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
for element in iterable:
if element:
return True
return False

Ex 1: Lists (works in a similar way for tuples and sets)
# all true except 0
l = [1, 3, 4, 0]
print(any(l)) # True

# both false
l = [0, False]
print(any(l)) # False

# all false except 5
l = [0, False, 5]
print(any(l)) # True

# empty
l = []
print(any(l)) # False

Ex 2: Strings
# all elements are true
s = "This is good"
print(any(s)) # True

# all elements are true
s = '000'
print(any(s)) # True

# false (empty iterable)
s = ''
print(any(s)) # False

Ex 3: Dictionaries (return False if all keys, not values, are false, or the dictionary is empty; else return True)
# 0 is False
d = {0: 'False'}
print(any(d)) # False

# 1 is True
d = {0: 'False', 1: 'True'}
print(any(d)) # True

# 0 and False are false
d = {0: 'False', False: 0}
print(any(d)) # False

# iterable is empty
d = {}
print(any(d)) # False

# 0 is False
# '0' is True
d = {'0': 'False'}
print(any(d)) # True


ascii(object)

Description: The ascii() method returns a string containing a printable representation of an object. It escapes the non-ASCII characters in the string using \x, \u or \U escapes.

Syntax: The syntax of ascii() is: ascii(object)

Parameters: The ascii() method takes an object (like: strings, list etc).

Return value: It returns a string containing a printable representation of an object. For example, ö is changed to \xf6n, is changed to \u221a. The non-ASCII characters in the string are escaped using \x, \u or \U.

Examples:

Ex 0: Documentation

As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u or \U escapes. This generates a string similar to that returned by repr() in Python 2.


Ex 1: Basic usage (encoding and decoding simple strings)
normalText = 'Python is interesting'
print(ascii(normalText))

otherText = 'Pythön is interesting'
print(ascii(otherText))

print('Pyth\xf6n is interesting')

Output:

'Python is interesting'
'Pyth\xf6n is interesting'
Pythön is interesting

Ex 2: Applying ascii() to each element of a list
randomList = ['Python', 'Pythön', 5]
print(ascii(randomList))

Output:

['Python', 'Pyth\xf6n', 5]


bin(x)

Description: The bin() method converts and returns the binary equivalent string of a given integer. If the parameter isn't an integer, it has to implement __index__() method to return an integer.

Syntax: The syntax of bin() method is: bin(num)

Parameters: The bin() method takes a single parameter num: an integer number whose binary equivalent is to be calculated. If not an integer, should implement __index__() method to return an integer.

Return value: bin() method returns the binary string equivalent to the given integer. If not specified an integer, it raises a TypeError exception highlighting the type cannot be interpreted as an integer.

Examples:

Ex 0: Documentation

Convert an integer number to a binary string prefixed with 0b.

The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

If prefix 0b is desired or not, you can use either of the following ways:

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

See also format() for more information.


Ex 1: Converting an integer to binary using bin()
number = 5
print('The binary equivalent of 5 is:', bin(number))

Output:

The binary equivalent of 5 is: 0b101

The prefix 0b represents that the result is a binary string.


Ex 2: Convert an object to binary implementing __index__() method
class Quantity:
apple = 1
orange = 2
grapes = 2

def __index__(self):
return self.apple + self.orange + self.grapes

print('The binary equivalent of quantity is:', bin(Quantity()))

Output:

The binary equivalent of quantity is: 0b101

Here, we've sent an object of class Quantity to the bin() method. The bin() method doesn't raise an error even if the object Quantity is not an integer. This is because we have implemented the __index__() method which returns an integer (sum of fruit quantities). This integer is then supplied to the bin() method.


Ex 3: Multiple one-line examples
print(bin(4))             # 0b100
print(format(4,'#b')) # 0b100
print(f'{4:#b}') # 0b100
print(format(4,'b')) # 100
print(f'{4:b}') # 100
print(int('100', 2)) # 4
print(int('0b100', 2)) # 4


bool([x])

Description: The bool() function converts a value to Boolean (True or False) using the standard truth testing procedure.

Syntax: The syntax of bool() is: bool([value])

Parameters: It's not mandatory to pass a value to bool(). If you do not pass a value, bool() returns False. In general use, bool() takes a single parameter value.

Return value: bool() returns

  • False if the value is omitted or false
  • True if the value is true

Falsy values in Python: Recall that all values in Python are considered truthy except for the following which are falsy (more can be found in the docs on truth value testing):

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] - an empty list
  • {} - an empty dict
  • () - an empty tuple
  • '' - an empty str
  • b'' - an empty bytes
  • set() - an empty set
  • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0

Examples:

Ex 0: Documentation

Return a Boolean value (i.e., one of True or False). If x is false or omitted, this (i.e., bool() or bool(x) where x is false) returns False; otherwise it returns True.

x is converted using the standard truth testing procedure. The bool class is a subclass of int (see Numeric Types — int, float, complex). It cannot be subclassed further. Its only instances are False and True (see Boolean Values).


Ex 1: Basic usage on a variety of inputs
test = []
print(test,'is',bool(test))

test = [0]
print(test,'is',bool(test))

test = 0.0
print(test,'is',bool(test))

test = None
print(test,'is',bool(test))

test = True
print(test,'is',bool(test))

test = 'Easy string'
print(test,'is',bool(test))

Output:

[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True

Changed in version 3.7: x is now a positional-only parameter.


breakpoint(*args, **kws)

Description: See documentation below. The primary purpose is to be able to drop into the debugger at the call site without the overhead of having to import the pdb module.

Examples:

Ex 0: Documentation

This function drops you into the debugger at the call site.

Specifically, it calls sys.breakpointhook(), passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don't have to explicitly import pdb or type as much code to enter the debugger. However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice.

Raises an auditing event builtins.breakpoint with argument breakpointhook.

New in version 3.7.


Ex 1: Basic usage of breakpoint

Consider the following somewhat verbose silly example (note how breakpoint would allow us to avoid the usage of pdb below):

import pdb

def add(num1, num2):
# code tries to run until it hits the set_trace for pdb below
pdb.set_trace()
# within the debugger, we can test out what is going on thus far
# for example, entering num1 will tell us what num1 is at this point (same for num2)
# pdb really has a ton of helpful things; for example,
# simply typing 'help' shows documented commands you can use within the interactive debugger
# if you see a command you're not sure about, then simply type 'help <command>'
# we can type 'step' to step through our code
# right now typing 'some_var' within pdb would give us a NameError since we have not reached that line yet
# we can run 'continue' to continue through the code until we hit a return
# the 'a' command is also helpful since it will give you the arguments of the function you're in at that point in execution
# you can interactively change the value of different arguments to test things out
# the 'w' command will give you context for debugging
# finally 'exit' will let you exit the debugger
some_var = 4 * 5
print(some_var)
return num1 + num2

add(4, 'string')

We can certainly use pdb, the Python debugging module in the standard library, as illustrated above, but it can be rather cumbersome to import a module just to do some debugging. For the sake of convenience, you can get everything above by simply removing the import pdb statement as well as changing the line pdb.set_trace() to breakpoint(). We then end up with the exact some functionality but avoid importing a module:

def add(num1, num2):
breakpoint()
some_var = 4 * 5
print(some_var)
return num1 + num2

add(4, 'string')


NOTE: Some notes about str, byte, bytearray, and Unicode strings

The following notes largely come from [3] in a variety of places.

Overview: The normal str string object is an immutable (unchangeable) sequence of characters accessed by offset (position). Its characters are code point ordinals in the underlying character set, and individual characters are string objects of length 1.

The full string object model varies across lines.

Python 3.X has three string types with similar interfaces:

  • str: An immutable sequence of characters, used for all text—-both ASCII and richer Unicode.
  • bytes: An immutable sequence of short integers, used for the byte values of binary data.
  • bytearray: A mutable variant of bytes.

The following literal forms and calls make specialized strings:

  • b'...': bytes string literal in Python 3.X: sequence of 8-bit byte values representing raw binary data.
  • bytearray(...): bytearray string construction: a mutable variant of bytes.
  • str(), bytes(), bytearray(): Create strings from objects, with possible Unicode encoding/decoding in Python 3.X.

byte and bytearray methods: Python 3.X bytes and bytearray string types have method sets similar to that of the normal str type, but do not overlap exactly due to differing roles. (str is Unicode text, bytes is raw binary data, and bytearray is mutable.) In the following, run in Python 3.9, set(dir(X)) – set(dir(Y)) computes attributes unique to X:

>>> set(dir(str)) - set(dir(bytes))
{
'isidentifier', 'encode', 'isnumeric',
'format', 'format_map', 'isdecimal',
'isprintable', 'casefold'
}

>>> set(dir(bytes)) - set(dir(str))
{
'fromhex', 'decode', 'hex'
}

>>> set(dir(bytearray)) - set(dir(bytes))
{
'clear', '__setitem__', '__iadd__',
'reverse', 'pop', 'insert',
'__delitem__', 'append', '__imul__',
'__alloc__', 'remove', 'extend',
'copy'
}

Of note:

  • str does not support Unicode decoding (it is already decoded text), but may be encoded to bytes.
  • bytes and bytearray do not support Unicode encoding (they are raw bytes, including both media and already encoded text), but may be decoded to str.
  • bytes and bytearray do not support string formatting (implemented by str.format).
  • bytearray has extra mutable in-place methods and operators similar to list (e.g., append, +=).

Unicode strings: All text is Unicode text, including text encoded with one character per byte (8 bits) in the ASCII scheme. Python supports richer character sets and encoding schemes with Unicode--strings which may use multiple bytes to represent characters in memory, and which translate text to and from various encodings on files. This support differs in Python lines. Python 3.X treats all text as Unicode and represents binary data separately, while Python 2.X distinguishes 8-bit text (and data) from possibly wider Unicode text.

In Python 3.X, the normal str type and 'ccc' literal represents all text, both 8-bit and richer Unicode. str is an immutable sequence of characters-—decoded Unicode code points (ordinal identifiers) in memory.

A separate bytes type and b'ccc' literal represents binary data byte values, including media and encoded Unicode text. bytes is an immutable sequence of small integers (8-bit byte values), but supports most str operations, and prints content as ASCII characters when possible. An additional bytearray type is a mutable variant of bytes, with extra list-like methods for in-place changes.

Also in 3.X, normal files created by open() imply str and bytes objects for content in text and binary mode, respectively. In text mode, files automatically encode on output and decode on input.

Unicode support in Python 3.X: Python 3.X allows non-ASCII characters to be coded in strings with hex (\x) and both 16- and 32-bit Unicode (\u, \U) escapes. In addition, chr() supports Unicode character codes:

>>> 'A\xE4B'
'AäB'

>>> 'A\u00E4B'
'AäB'

>>> 'A\U000000E4B'
'AäB'

>>> chr(0xe4)
'ä'

byte and bytearray strings: Python 3.X bytes and bytearray string objects represent 8-bit binary data (including encoded Unicode text); are printed as ASCII text when possible; and support most normal str string operations including methods and sequence operations (but not string formatting). For example, the code block

B = b'spam'
print(B)

B = bytes('spam', 'utf-8')
print(B)

print(B[0])
print(ord('s'))

print(B + b'abc')
print(B.split(b'a'))

print(list(B))
print([ chr(c) for c in B ])

print([ ord(c) for c in 'spam' ])
print([ c for c in 'spam' ])

yields the following output (newlines for clarity):

b'spam'
b'spam'

115
115

b'spamabc'
[b'sp', b'm']

[115, 112, 97, 109]
['s', 'p', 'a', 'm']

[115, 112, 97, 109]
['s', 'p', 'a', 'm']

bytearray additionally supports list-like mutable operations:

BA = bytearray(b'spam')
print(BA)
print(BA[0])
print(BA + b'abc')

BA[0] = 116 # Mutability
BA.append(115) # List methods
print(BA)

yields:

bytearray(b'spam')
115
bytearray(b'spamabc')

bytearray(b'tpams')

bytearray([source[, encoding[, errors]]])

Description: The bytearray() method returns a bytearray object which is an array of the given bytes.

prime_numbers = [2, 3, 5, 7]

# convert list to bytearray
byte_array = bytearray(prime_numbers)
print(byte_array)

# Output: bytearray(b'\x02\x03\x05\x07')

Syntax: The syntax of bytearray() method is: bytearray([source[, encoding[, errors]]]). The bytearray() method returns a bytearray object (i.e., array of bytes) which is a mutable sequence of integers in the range 0 <= x < 256. If you want an immutable version, then use the bytes() method.

Parameters: bytearray() takes three optional parameters:

  • source (Optional) - source to initialize the array of bytes.
  • encoding (Optional) - if the source is a string, the encoding of the string.
  • errors (Optional) - if the source is a string, the action to take when the encoding conversion fails

The source parameter can be used to initialize the byte array in the following ways:

TypeDescription
StringConverts the string to bytes using str.encode(). Must also provide encoding and optionally errors
IntegerCreates an array of provided size, all initialized to null
ObjectA read-only buffer of the object will be used to initialize the byte array
IterableCreates an array of size equal to the iterable count and initialized to the iterable elements. Must be iterable of integers between 0 <= x < 256
No source (arguments)Creates an array of size 0.

Return value: The bytearray() method returns an array of bytes of the given size and initialization values.

Examples:

Ex 0: Documentation

Return a new array of bytes.

The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.

The optional source parameter can be used to initialize the array in a few different ways:

  • If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
  • If it is an integer, the array will have that size and will be initialized with null bytes.
  • If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
  • If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.


Ex 1: Array of bytes from a string
string = "Python is interesting."

# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
print(arr)

Output:

bytearray(b'Python is interesting.')

Ex 2: Array of bytes of given integer size
size = 5

arr = bytearray(size)
print(arr)

Output:

bytearray(b'\x00\x00\x00\x00\x00')

Ex 3: Array of bytes from an iterable list
rList = [1, 2, 3, 4, 5]

arr = bytearray(rList)
print(arr)

Output:

bytearray(b'\x01\x02\x03\x04\x05')


bytes([source[, encoding[, errors]]])

Description: The bytes() method returns an immutable bytes object initialized with the given size and data.

message = 'Python is fun'

# convert string to bytes
byte_message = bytes(message, 'utf-8')
print(byte_message)

# Output: b'Python is fun'

Syntax: The syntax of bytes() method is

bytes([source[, encoding[, errors]]])

bytes() method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256. If you want to use the mutable version, use the bytearray() method.

Parameters: bytes() takes three optional parameters:

  • source (Optional) - source to initialize the array of bytes.
  • encoding (Optional) - if the source is a string, the encoding of the string.
  • errors (Optional) - if the source is a string, the action to take when the encoding conversion fails

The source parameter can be used to initialize the byte array in the following ways:

TypeDescription
StringConverts the string to bytes using str.encode(). Must also provide encoding and optionally errors
IntegerCreates an array of provided size, all initialized to null
ObjectA read-only buffer of the object will be used to initialize the byte array
IterableCreates an array of size equal to the iterable count and initialized to the iterable elements. Must be iterable of integers between 0 <= x < 256
No source (arguments)Creates an array of size 0.

Return value: The bytes() method returns a bytes object of the given size and initialization values.

Return value:

Examples:

Ex 0: Documentation

Return a new "bytes" object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.

Accordingly, constructor arguments are interpreted as for bytearray().

Bytes objects can also be created with literals, see String and Bytes literals.

See also Binary Sequence Types — bytes, bytearray, memoryview, Bytes Objects, and Bytes and Bytearray Operations.


Ex 1: Convert string to bytes
string = "Python is interesting."

# string with encoding 'utf-8'
arr = bytes(string, 'utf-8')
print(arr)

Output:

b'Python is interesting.'

Ex 2: Create a byte of given integer size
size = 5

arr = bytes(size)
print(arr)

Output:

b'\x00\x00\x00\x00\x00'

Ex 3: Convert iterable list to bytes
rList = [1, 2, 3, 4, 5]

arr = bytes(rList)
print(arr)

Output:

b'\x01\x02\x03\x04\x05'


callable(object)

Description: The callable() method returns True if the object passed appears callable. If not, it returns False.

Syntax: The syntax of callable() is: callable(object)

Parameters: callable() method takes a single argument: object

Return value: The callable() method returns:

  • True - if the object appears callable
  • False - if the object is not callable.

It important to remember that, even if callable() is True, call to the object may still fail.

However, if callable() returns False, call to the object will certainly fail.

Examples:

Ex 0: Documentation

Return True if the object argument appears callable, False if not.

If this returns True, it is still possible that a call fails, but if it is False, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__() method.

New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.


Ex 1: How callable() works
x = 5
print(callable(x))

def testFunction():
print("Test")

y = testFunction
print(callable(y))

Output:

False
True

Here, the object x is not callable. And, the object y appears to be callable (but may not be callable).


Ex 2: Callable object
class Foo:
def __call__(self):
print('Print Something')

print(callable(Foo))

Output:

True

The instance of Foo class appears to be callable (and is callable in this case).

class Foo:
def __call__(self):
print('Print Something')

InstanceOfFoo = Foo()

# Prints 'Print Something'
InstanceOfFoo()

Ex 3: Object appears to be callable but is not callable
class Foo:
def printLine(self):
print('Print Something')

print(callable(Foo))

Output:

True

The instance of Foo class appears to be callable but it's not callable. The following code will raise an error.

class Foo:
def printLine(self):
print('Print Something')

print(callable(Foo))

InstanceOfFoo = Foo()
# Raises an Error
# 'Foo' object is not callable
InstanceOfFoo()

Output:

True
Traceback (most recent call last):
File "", line 10, in
TypeError: 'Foo' object is not callable


chr(i)

Description: The chr() method returns a character (a string) from an integer (represents unicode code point of the character).

Syntax: The syntax of chr() is: chr(i)

Parameters: The chr() method takes a single parameter, an integer i. The valid range of the integer is from 0 through 1,114,111.

Return value: chr() returns a character (a string) whose Unicode code point is the integer i. If the integer i is outside the range, ValueError will be raised.

Examples:

Ex 0: Documentation

Returns a one-character string whose Unicode code point is the integer i.

For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.


Ex 1: How chr() works
print(chr(97))
print(chr(65))
print(chr(1200)

Output:

a
A
Ұ

Ex 2: Integer passed to chr() is out of the range
print(chr(-1))

Output:

Traceback (most recent call last):
File "", line 1, in
ValueError: chr() arg not in range(0x110000)

When you run the program, ValueError is raised. It's because the argument passed to chr() method is out of the range.


ASCII Table
DecHexOctBinaryHTMLCharDescription
00000000000000&#0;NULNull
10100100000001&#1;SOHStart of Header
20200200000010&#2;STXStart of Text
30300300000011&#3;ETXEnd of Text
40400400000100&#4;EOTEnd of Transmission
50500500000101&#5;ENQEnquiry
60600600000110&#6;ACKAcknowledge
70700700000111&#7;BELBell
80801000001000&#8;BSBackspace
90901100001001&#9;HTHorizontal Tab
100A01200001010&#10;LFLine Feed
110B01300001011&#11;VTVertical Tab
120C01400001100&#12;FFForm Feed
130D01500001101&#13;CRCarriage Return
140E01600001110&#14;SOShift Out
150F01700001111&#15;SIShift In
161002000010000&#16;DLEData Link Escape
171102100010001&#17;DC1Device Control 1
181202200010010&#18;DC2Device Control 2
191302300010011&#19;DC3Device Control 3
201402400010100&#20;DC4Device Control 4
211502500010101&#21;NAKNegative Acknowledge
221602600010110&#22;SYNSynchronize
231702700010111&#23;ETBEnd of Transmission Block
241803000011000&#24;CANCancel
251903100011001&#25;EMEnd of Medium
261A03200011010&#26;SUBSubstitute
271B03300011011&#27;ESCEscape
281C03400011100&#28;FSFile Separator
291D03500011101&#29;GSGroup Separator
301E03600011110&#30;RSRecord Separator
311F03700011111&#31;USUnit Separator
322004000100000&#32;spaceSpace
332104100100001&#33;!exclamation mark
342204200100010&#34;"double quote
352304300100011&#35;#number
362404400100100&#36;$dollar
372504500100101&#37;%percent
382604600100110&#38;&ampersand
392704700100111&#39;'single quote
402805000101000&#40;(left parenthesis
412905100101001&#41;)right parenthesis
422A05200101010&#42;*asterisk
432B05300101011&#43;+plus
442C05400101100&#44;,comma
452D05500101101&#45;-minus
462E05600101110&#46;.period
472F05700101111&#47;/slash
483006000110000&#48;0zero
493106100110001&#49;1one
503206200110010&#50;2two
513306300110011&#51;3three
523406400110100&#52;4four
533506500110101&#53;5five
543606600110110&#54;6six
553706700110111&#55;7seven
563807000111000&#56;8eight
573907100111001&#57;9nine
583A07200111010&#58;:colon
593B07300111011&#59;;
603C07400111100&#60;<less than
613D07500111101&#61;=equality sign
623E07600111110&#62;>greater than
633F07700111111&#63;?question mark
644010001000000&#64;@at sign
654110101000001&#65;A
664210201000010&#66;B
674310301000011&#67;C
684410401000100&#68;D
694510501000101&#69;E
704610601000110&#70;F
714710701000111&#71;G
724811001001000&#72;H
734911101001001&#73;I
744A11201001010&#74;J
754B11301001011&#75;K
764C11401001100&#76;L
774D11501001101&#77;M
784E11601001110&#78;N
794F11701001111&#79;O
805012001010000&#80;P
815112101010001&#81;Q
825212201010010&#82;R
835312301010011&#83;S
845412401010100&#84;T
855512501010101&#85;U
865612601010110&#86;V
875712701010111&#87;W
885813001011000&#88;X
895913101011001&#89;Y
905A13201011010&#90;Z
915B13301011011&#91;[left square bracket
925C13401011100&#92;\backslash
935D13501011101&#93;]right square bracket
945E13601011110&#94;^caret / circumflex
955F13701011111&#95;_underscore
966014001100000&#96;`grave / accent
976114101100001&#97;a
986214201100010&#98;b
996314301100011&#99;c
1006414401100100&#100;d
1016514501100101&#101;e
1026614601100110&#102;f
1036714701100111&#103;g
1046815001101000&#104;h
1056915101101001&#105;i
1066A15201101010&#106;j
1076B15301101011&#107;k
1086C15401101100&#108;l
1096D15501101101&#109;m
1106E15601101110&#110;n
1116F15701101111&#111;o
1127016001110000&#112;p
1137116101110001&#113;q
1147216201110010&#114;r
1157316301110011&#115;s
1167416401110100&#116;t
1177516501110101&#117;u
1187616601110110&#118;v
1197716701110111&#119;w
1207817001111000&#120;x
1217917101111001&#121;y
1227A17201111010&#122;z
1237B17301111011&#123;{left curly bracket
1247C17401111100&#124;|vertical bar
1257D17501111101&#125;}right curly bracket
1267E17601111110&#126;~tilde
1277F17701111111&#127;DELdelete

Extended ASCII Table
DecHexBinaryHTMLChar
1288010000000-€
1298110000001-
1308210000010-‚
1318310000011-ƒ
1328410000100-„
1338510000101-…
1348610000110-†
1358710000111-‡
1368810001000-ˆ
1378910001001-‰
1388A10001010-Š
1398B10001011-‹
1408C10001100-Œ
1418D10001101-
1428E10001110-Ž
1438F10001111-
1449010010000-
1459110010001-‘
1469210010010-’
1479310010011-“
1489410010100-”
1499510010101-•
1509610010110-–
1519710010111-—
1529810011000-˜
1539910011001-™
1549A10011010-š
1559B10011011-›
1569C10011100-œ
1579D10011101-
1589E10011110-ž
1599F10011111-Ÿ
160A010100000&#160;
161A110100001&#161;¡
162A210100010&#162;¢
163A310100011&#163;£
164A410100100&#164;¤
165A510100101&#165;¥
166A610100110&#166;¦
167A710100111&#167;§
168A810101000&#168;¨
169A910101001&#169;©
170AA10101010&#170;ª
171AB10101011&#171;«
172AC10101100&#172;¬
173AD10101101&#173;­
174AE10101110&#174;®
175AF10101111&#175;¯
176B010110000&#176;°
177B110110001&#177;±
178B210110010&#178;²
179B310110011&#179;³
180B410110100&#180;´
181B510110101&#181;µ
182B610110110&#182;
183B710110111&#183;·
184B810111000&#184;¸
185B910111001&#185;¹
186BA10111010&#186;º
187BB10111011&#187;»
188BC10111100&#188;¼
189BD10111101&#189;½
190BE10111110&#190;¾
191BF10111111&#191;¿
192C011000000&#192;À
193C111000001&#193;Á
194C211000010&#194;Â
195C311000011&#195;Ã
196C411000100&#196;Ä
197C511000101&#197;Å
198C611000110&#198;Æ
199C711000111&#199;Ç
200C811001000&#200;È
201C911001001&#201;É
202CA11001010&#202;Ê
203CB11001011&#203;Ë
204CC11001100&#204;Ì
205CD11001101&#205;Í
206CE11001110&#206;Î
207CF11001111&#207;Ï
208D011010000&#208;Ð
209D111010001&#209;Ñ
210D211010010&#210;Ò
211D311010011&#211;Ó
212D411010100&#212;Ô
213D511010101&#213;Õ
214D611010110&#214;Ö
215D711010111&#215;×
216D811011000&#216;Ø
217D911011001&#217;Ù
218DA11011010&#218;Ú
219DB11011011&#219;Û
220DC11011100&#220;Ü
221DD11011101&#221;Ý
222DE11011110&#222;Þ
223DF11011111&#223;ß
224E011100000&#224;à
225E111100001&#225;á
226E211100010&#226;â
227E311100011&#227;ã
228E411100100&#228;ä
229E511100101&#229;å
230E611100110&#230;æ
231E711100111&#231;ç
232E811101000&#232;è
233E911101001&#233;é
234EA11101010&#234;ê
235EB11101011&#235;ë
236EC11101100&#236;ì
237ED11101101&#237;í
238EE11101110&#238;î
239EF11101111&#239;ï
240F011110000&#240;ð
241F111110001&#241;ñ
242F211110010&#242;ò
243F311110011&#243;ó
244F411110100&#244;ô
245F511110101&#245;õ
246F611110110&#246;ö
247F711110111&#247;÷
248F811111000&#248;ø
249F911111001&#249;ù
250FA11111010&#250;ú
251FB11111011&#251;û
252FC11111100&#252;ü
253FD11111101&#253;ý
254FE11111110&#254;þ
255FF11111111&#255;ÿ


@classmethod

Description: Returns a class method for a function.

A class method receives the class as implicit first argument, just like an instance method receives the instance (i.e., self). To declare a class method, use this idiom:

class C:
@classmethod
def f(cls, arg1, arg2, ...): ...

The @classmethod form is a function decorator – see Function definitions for details.

A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod(). For more information on class methods, see The standard type hierarchy.

Changed in version 3.9: Class methods can now wrap other descriptors such as property().

Examples: The classmethod syntax used to be classmethod(function) but was considered un-Pythonic; thus, in newer Python versions, you can use the @classmethod decorator for classmethod definitions.

Ex 1: Usage notes and difference from staticmethod

A class method is a method that is bound to a class rather than its object. It doesn't require creation of a class instance, much like staticmethod.

The difference between a static method and a class method is:

  • Static method knows nothing about the class and just deals with the parameters
  • Class method works with the class since its parameter is always the class itself.

The class method can be called both by the class and its object: Class.classmethod() or Class().classmethod(). Regardless, the class method is always attached to a class with the first argument as the class itself, cls:

class C:
@classmethod
def f(cls, arg1, arg2, ...): ...

Ex 2: Simple and equivalent usage of classmethod(function) and @classmethod

The code block

class Person:
age = 25

def printAge(cls):
print('The age is:', cls.age)

# create printAge class method
Person.printAge = classmethod(Person.printAge)
Person.printAge()

and

class Person:
age = 25

# create printAge class method
@classmethod
def printAge(cls):
print('The age is:', cls.age)

Person.printAge()

are effectively the same and have the following output:

The age is: 25

Notes: We have a Person class with a member variable age assigned to 25. We also have a function printAge that takes a single parameter cls and not self which is what we would usually take; that is, cls accepts the Person class as a parameter rather than Person instance we typically refer to by self.

For the classmethod(function) syntaxm, we pass the method Person.printAge as an argument to the classmethod function. This converts the method to a class method so that it accepts the first parameter as a class (i.e., Person). We then call printAge without creating a Person object like we do for static methods. This prints the class variable age.

The @classmethod function decorator form allows our code to be cleaner and is the more modern way to write Python code.


Ex 3: Using @classmethod to create a factory method

Factory methods are those methods that return a class object (similar to the __init__ constructor method which initializes the new instance of the class, self) for different use cases.

It is similar to function overloading in C++. Since, Python doesn't have anything as such, class methods and static methods are used.

from datetime import date

# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)

def display(self):
print(self.name + "'s age is: " + str(self.age))

person = Person('Adam', 19)
person.display()

person1 = Person.fromBirthYear('John', 1985)
person1.display()

Output:

Adam's age is: 19
John's age is: 36

The code block that produces the output above has two class instance creators, a constructor (i.e., __init__) and a fromBirthYear method.

The constructor takes its normal parameters, name and age in this case, while fromBirthYear takes cls (i.e., the Person class), name, and birthYear, and calculates the current age by subtracting the birthYear from the current year and returns the newly created class instance (the fact that fromBirthYear returns a new class instance is what makes it a factory method).

The fromBirthYear method takes the Person class (not a Person instance or object) as the first parameter, cls, and returns the constructor by calling cls(name, date.today().year - birthYear), which is equivalent to Person(name, date.today().year - birthYear).

Before the definition of the fromBirthYear method, we see @classmethod. This is called a decorator for converting fromBirthYear to a class method as classmethod().


Ex 4: How @classmethod works in the context of inheritance (and why @staticmethod would fail)

Whenever you derive a class from implementing a factory method as a class method, it ensures correct instance creation of the derived class. If, however, a factory method is implemented as a static method, then the instance created will always be hardcoded as the base class.

But when you use a class method, it creates the correct instance of the derived class. This is easier to understand by means of an example:

from datetime import date

# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

@staticmethod
def fromFathersAge(name, fatherAge, fatherPersonAgeDiff):
# Cannot return cls(arg1, arg2, ...) or something like that since
# static methods know nothing about the class and deal strictly with the parameters
return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)

@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)

def display(self):
print(self.name + "'s age is: " + str(self.age))

class Man(Person):
sex = 'Male'

man_w_class_method = Man.fromBirthYear('John', 1985)
print(man_w_class_method)
print(isinstance(man_w_class_method, Man))
print(isinstance(man_w_class_method, Person))

man_w_static_method = Man.fromFathersAge('Bruce', 1965, 20)
print(man_w_static_method)
print(isinstance(man_w_static_method, Man))
print(isinstance(man_w_static_method, Person))

Output:

<__main__.Man object at 0x10dde4af0>
True
True

<__main__.Person object at 0x10dde49d0>
False
True

Using @staticmethod for the fromFathersAge factory method forces us to hardcode the instance tape (i.e., Person) during creation. This clearly causes a problem when Man inherits from Person.

The fromFathersAge method doesn't return a Man object but its base class, a hardcoded Person object. This violates the OOP paradigm. Using @classmethod for the fromBirthYear factory method can ensure the OOP-ness of the code since this method takes the first parameter as the class itself and calls its factory method.



compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Description: This StackOverflow answer gives a great somewhat dumbed down explanation (actual documentation reproduced below as an example): compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

  1. compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid. Used for a single expression.
  2. compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here. Used for an entire module.
  3. compile(string, '', 'single') is like the exec mode, but it will ignore everything except for the first statement. Note that an if/else statement with its results is considered a single statement. Used for one single statement. [Does not seem to be particularly useful.]

Examples:

Ex 0: Official documentation

Syntax: compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Compile the source into a code or AST object. Code objects can be executed by exec() or eval(). source can either be a normal string, a byte string, or an AST object. Refer to the ast module documentation for information on how to work with AST objects.

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn't read from a file ('<string>' is commonly used).

The mode argument specifies what kind of code must be compiled; it can be 'exec' if source consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than None will be printed).

The optional arguments flags and dont_inherit control which compiler options should be activated and which future features should be allowed. If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling compile(). If the flags argument is given and dont_inherit is not (or is zero) then the compiler options and the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it – the flags (future features and compiler options) in the surrounding code are ignored.

Compiler options and future statements are specified by bits which can be bitwise ORed together to specify multiple options. The bitfield required to specify a given future feature can be found as the compiler_flag attribute on the _Feature instance in the __future__ module. Compiler flags can be found in ast module, with PyCF_ prefix.

The argument optimize specifies the optimization level of the compiler; the default value of -1 selects the optimization level of the interpreter as given by -O options. Explicit levels are 0 (no optimization; __debug__ is true), 1 (asserts are removed, __debug__ is false) or 2 (docstrings are removed too).

This function raises SyntaxError if the compiled source is invalid, and ValueError if the source contains null bytes.

If you want to parse Python code into its AST representation, see ast.parse().

Raises an auditing event compile with arguments source and filename. This event may also be raised by implicit compilation.

Note: When compiling a string with multi-line code in 'single' or 'eval' mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the code module.

Warning: It is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Python's AST compiler.

Changed in version 3.2: Allowed use of Windows and Mac newlines. Also input in 'exec' mode does not have to end in a newline anymore. Added the optimize parameter.

Changed in version 3.5: Previously, TypeError was raised when null bytes were encountered in source.

New in version 3.8: ast.PyCF_ALLOW_TOP_LEVEL_AWAIT can now be passed in flags to enable support for top-level await, async for, and async with.


Ex 1: Examples and notes involving single, eval, and exec modes

As this helpful post illustrates, compile is meant to compile a source string from filename into a code object, which can later be executed by eval() or exec(). filename is simply used for run-time error messages. It is recommended to use '<string>' as the filename if source was not read from a file. mode is a string which indicates the compilation mode with the following options available:

  • 'single': indicates compilation is intended for a single statement
  • 'eval': indicates compilation is intended for a single expression
  • 'exec': indicates compliation is intended for an entire Python module

First, note that all expressions are statements (e.g., 5+5) in Python but not all statements are expressions (e.g., x = 5+5). Second, note that use of compile is rather infrequent. If you do find yourself using compile then you will likely use the exec mode. In any case, let's explore a few trivial use cases to illustrate usage.

Usage of compile with mode set to 'single': Suppose you have two files, example_usage.py and simple_module.py, in the same directory with contents as follows

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_single = compile(contents, 'simple_module.py', 'single')
exec(code_obj_single)
# file: simple_module.py
import json

def myfn(mydict):
return json.dumps(mydict)

def myfn2():
return myfn({"x": 30})

print(myfn2())

If we attempt to run example_usage.py, then we will get an error:

File "simple_module.py", line 1
import json
^
SyntaxError: multiple statements found while compiling a single statement

The error is exactly what it sounds like: Multiple statements currently exist in the simple_module.py file, but compile with the mode option set to 'single' is only meant to compile a single statement. Consider updating the example_usage.py and simple_module.py files as follows:

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_single = compile(contents, 'simple_module.py', 'single')
exec(code_obj_single)
print(json)
# file: simple_module.py
import json

Note that now simple_module.py only has a single statement in it, namely import json. We compile that single statement in example_usage.py and we can see that the statement has been executed via the print(json) statement:

<module 'json' from '/Users/danielfarlow/.pyenv/versions/3.9.4/lib/python3.9/json/__init__.py'>

Usage of compile with mode set to 'eval': Suppose you have two files, example_usage.py and simple_module.py, in the same directory with contents as follows

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
eval(code_obj_eval)
# file: simple_module.py
import json

If we attempt to run example_usage.py, then we will get an error:

File "simple_module.py", line 1
import json
^
SyntaxError: invalid syntax

Why do we get this error? Because when 'eval' is chosen as the mode option we can only use an expression (singular) as the source. Remember that all expressions are statements but not all statements are expressions (expressions must resolve to a value). Suppose you change example_usage.py and simple_module.py in the following manner:

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
# file: simple_module.py
"2+3"
"5+10"

Will we get an error when running the example_usage.py file? Yes:

File "simple_module.py", line 2
"5+10"
^
SyntaxError: invalid syntax

Why do we get this error? Because we have more than one expression. Update the simple_module.py file to have "2+3" as its only line, and update the example_usage.py as well:

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
num = eval(code_obj_eval)
print(num)
# file: simple_module.py
"2+3"

What do you think the output will be upon running the example_usage.py file? You might be surprised when you get 2+3 as the output. Why didn't eval actually evaluate "2+3" like we might have suspected? The easiest way to see this is probably by means of updating the example_usage.py file and running it again:

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()
print("===== BEGIN READING FILE CONTENTS =====")
print(dir(contents))
print(type(contents))
print("===== END READING FILE CONTENTS =====")

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
print("===== BEGIN ATTRIBUTES OF COMPILED FILE CONTENTS OBJECT =====")
print(dir(code_obj_eval))
print("===== END ATTRIBUTES OF COMPILED FILE CONTENTS OBJECT =====")
print("Type of code object: ", type(code_obj_eval))
print("Type of evaluated code object: ", type(eval(code_obj_eval)))
# file: simple_module.py
"2+3"

Output:

===== BEGIN READING FILE CONTENTS =====
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
<class 'str'>
===== END READING FILE CONTENTS =====
===== BEGIN ATTRIBUTES OF COMPILED FILE CONTENTS OBJECT =====
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_posonlyargcount', 'co_stacksize', 'co_varnames', 'replace']
===== END ATTRIBUTES OF COMPILED FILE CONTENTS OBJECT =====
Type of code object: <class 'code'>
Type of evaluated code object: <class 'str'>

Some reflection seems to indicate that evaluating a code object essenitally "unwraps" the code object so we get the original code, namely a string in this case: "2+3". If we then want to evaluate that string, we must use eval again (hence twice):

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
num = eval(eval(code_obj_eval))
print(num)
# file: simple_module.py
"2+3"

The output is then more in line with what we might normally expect: 5. This behavior suggests a way we could avoid all of this rigmarole entirely: instead of writing "2+3" in the simple_module.py file, why not simply have 2+3 which will be stringified upon reading and then effectively evaluated when eval is applied after compile? We can avoid the double use of eval in such a case. Hence, we could have the following which would also have an output of 5 (note how there is now only one use of eval in example_usage.py and the "2+3" is now simply 2+3 in the simple_module.py file):

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_eval = compile(contents, 'simple_module.py', 'eval')
num = eval(code_obj_eval)
print(num)
# file: simple_module.py
2+3

Usage of compile with mode set to 'exec': If you find yourself using compile, then odds are this will be how you use it! Suppose you have two files, example_usage.py and simple_module.py, in the same directory with contents as follows:

# file: example_usage.py
with open('./simple_module.py') as f:
contents = f.read()

code_obj_exec = compile(contents, 'simple_module.py', 'exec')
exec(code_obj_exec)
# file: simple_module.py
import json

def myfn(mydict):
return json.dumps(mydict)

def myfn2():
return myfn({"x": 30})

print(myfn2())

If we attempt to run example_usage.py, then we will get what we might expect:

{"x": 30}

Furthermore, if we tried to execute a statement like print(myfn) from within example_usage.py, then we would get something like <function myfn at 0x10ba9fca0> which indicates the myfn function has been read in effectively from the simple_module.py file.



complex([real[, imag]])

Description: The complex() method returns a complex number when real and imaginary parts are provided, or it converts a string to a complex number.

The syntax of complex() is:

complex([real[, imag]])

In general, complex() method takes two parameters:

  • real - real part. If real is omitted, it defaults to 0.
  • imag - imaginary part. If imag is omitted, it defaults to 0.

If the first parameter passed to this method is a string, it will be interpreted as a complex number. In this case, the second parameter shouldn't be passed.

As suggested by the name, complex() method returns a complex number. If the string passed to this method is not a valid complex number, ValueError exception is raised.

Note: The string passed to complex() should be in the form real+imagj or real+imagJ.

Examples:

Ex 0: Documentation

Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.

For a general Python object x, complex(x) delegates to x.__complex__(). If __complex__() is not defined then it falls back to __float__(). If __float__() is not defined then it falls back to __index__().

Note: When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.

The complex type is described in Numeric Types — int, float, complex.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.8: Falls back to __index__() if __complex__() and __float__() are not defined.


Ex 1: How to create a complex number in Python?
z = complex(2, -3)
print(z)

z = complex(1)
print(z)

z = complex()
print(z)

z = complex('5-9j')
print(z)

Output:

(2-3j)
(1+0j)
0j
(5-9j)

Ex 2: Create complex Number Without Using complex()

It's possible to create a complex number without using the complex() method explicitly. For that, you have to put 'j' or 'J' after a number.

a = 2+3j
print('a =',a)
print('Type of a is',type(a))

b = -2j
print('b =',b)
print('Type of b is',type(a))

c = 0j
print('c =',c)
print('Type of c is',type(c))

Output:

a = (2+3j)
Type of a is <class 'complex'>
b = (-0-2j)
Type of b is <class 'complex'>
c = 0j
Type of c is <class 'complex'>


delattr(object, name)

Description: The delattr() built-in deletes an attribute from the provided object (if the object allows it).

The syntax of delattr() is:

delattr(object, name)

delattr() takes two parameters:

  • object - the object from which name attribute is to be removed
  • name - a string which must be the name of the attribute to be removed from the object

delattr() doesn't return any value (returns None). It only removes an attribute (if the object allows it).

Examples:

Ex 0: Documentation

This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object's attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar.


Ex 1: How delattr() works?
class Coordinate:
x = 10
y = -5
z = 0

point1 = Coordinate()

print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)

delattr(Coordinate, 'z')

print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)

# Raises Error
print('z = ',point1.z)

Output:

x =  10
y = -5
z = 0
--After deleting z attribute--
x = 10
y = -5
Traceback (most recent call last):
File "/Volumes/DEVFARLOW/development-and-engineering/python-learnings/mymodule.py", line 19, in <module>
print('z = ',point1.z)
AttributeError: 'Coordinate' object has no attribute 'z'

Ex 2: Deleting attribute using del operator

You can also delete attribute of an object using del operator.

class Coordinate:
x = 10
y = -5
z = 0

point1 = Coordinate()

print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)

# Deleting attribute z
del Coordinate.z

print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)

# Raises Attribute Error
print('z = ',point1.z)

The output of the program will be the same as in Example 1.



dict(**kwarg); dict(mapping, **kwarg); dict(iterable, **kwarg)

Description: The dict() constructor creates a dictionary in Python. Different forms of dict() constructors are:

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

Note: **kwarg lets you take an arbitrary number of keyword arguments.

A keyword argument is an argument preceded by an identifier (e.g., name=). Hence, the keyword argument of the form kwarg=value is passed to the dict() constructor to create dictionaries.

dict() doesn't return any value (returns None).

Examples:

Ex 0: Documentation
class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg)

Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class.

For other containers see the built-in list, set, and tuple classes, as well as the collections module.


Ex 1: Create dictionary using keyword arguments only
numbers = dict(x=5, y=0)
print('numbers =', numbers)
print(type(numbers))

empty = dict()
print('empty =', empty)
print(type(empty))

Output:

numbers = {'x': 5, 'y': 0}
<class 'dict'>
empty = {}
<class 'dict'>

Ex 2: Create dictionary using an iterable
# keyword argument is not passed
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)

# keyword argument is also passed
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)

# zip() creates an iterable in Python 3
numbers3 = dict(dict(zip(['x', 'y', 'z'], [1, 2, 3])))
print('numbers3 =',numbers3)

Output:

numbers1 = {'x': 5, 'y': -5}
numbers2 = {'x': 5, 'y': -5, 'z': 8}
numbers3 = {'x': 1, 'y': 2, 'z': 3}

Ex 3: Create dictionary using mapping
numbers1 = dict({'x': 4, 'y': 5})
print('numbers1 =',numbers1)

# you don't need to use dict() in above code
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =',numbers2)

# keyword argument is also passed
numbers3 = dict({'x': 4, 'y': 5}, z=8)
print('numbers3 =',numbers3)

Output:

numbers1 = {'x': 4, 'y': 5}
numbers2 = {'x': 4, 'y': 5}
numbers3 = {'x': 4, 'y': 5, 'z': 8}


dir([object])

Description: The dir() method tries to return a list of valid attributes of the object.

The syntax of dir() is:

dir([object])

dir() takes maximum of one object.

  • object (optional) - dir() attempts to return all attributes of this object.

dir() tries to return a list of valid attributes of the object.

  • If the object has __dir__() method, the method will be called and must return the list of attributes.
  • If the object doesn't have __dir__() method, this method tries to find information from the __dict__ attribute (if defined), and from type object. In this case, the list returned from dir() may not be complete.

If an object is not passed to dir() method, it returns the list of names in the current local scope.

Examples:

Ex 0: Documentation

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(), the function tries its best to gather information from the object's __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  • If the object is a module object, the list contains the names of the module's attributes.
  • If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
  • Otherwise, the list contains the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes.

The resulting list is sorted alphabetically. For example:

>>> import struct
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'struct']
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
...
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
>>>

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.


Ex 1: How dir() works?
number = [1, 2, 3]
print(dir(number))

print('\nReturn Value from empty dir()')
print(dir())

Output:

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Return Value from empty dir()
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'number']

Note how 'number' is included in the list when we print dir() with no provided object.


Ex 2: dir() on user-defined object
class Person:
def __dir__(self):
return ['age', 'name', 'salary']


teacher = Person()
print(dir(teacher))

Output:

['age', 'name', 'salary']


divmod(a,b)

Description: The divmod() method takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder.

The syntax of divmod() is:

divmod(x, y)

divmod() takes two parameters:

  • x - a non-complex number (numerator)
  • y - a non-complex number (denominator)

divmod() returns

  • (q, r) - a pair of numbers (a tuple) consisting of quotient q and remainder r

If x and y are integers, the return value from divmod() is same as (a // b, x % y).

If either x or y is a float, the result is (q, x % y). Here, q is the whole part of the quotient.

Examples:

Ex 0: Documentation

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).


Ex 1: How divmod() works in Python?
print('divmod(8, 3) = ', divmod(8, 3))
print('divmod(3, 8) = ', divmod(3, 8))
print('divmod(5, 5) = ', divmod(5, 5))

# divmod() with Floats
print('divmod(8.0, 3) = ', divmod(8.0, 3))
print('divmod(3, 8.0) = ', divmod(3, 8.0))
print('divmod(7.5, 2.5) = ', divmod(7.5, 2.5))
print('divmod(2.6, 0.5) = ', divmod(2.6, 0.5))

divmod(8, 3) = (2, 2) divmod(3, 8) = (0, 3) divmod(5, 5) = (1, 0) divmod(8.0, 3) = (2.0, 2.0) divmod(3, 8.0) = (0.0, 3.0) divmod(7.5, 2.5) = (3.0, 0.0) divmod(2.6, 0.5) = (5.0, 0.10000000000000009)



enumerate(iterable, start=0)

Description: The enumerate() method adds a counter to an iterable and returns it (the enumerate object).

languages = ['Python', 'Java', 'JavaScript']

enumerate_prime = enumerate(languages)

# convert enumerate object to list
print(list(enumerate_prime))

# Output: [(0, 'Python'), (1, 'Java'), (2, 'JavaScript')]

The syntax of enumerate() is:

enumerate(iterable, start=0)

enumerate() method takes two parameters:

  • iterable - a sequence, an iterator, or objects that supports iteration
  • start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.

enumerate() method adds counter to an iterable and returns it. The returned object is an enumerate object.

You can convert enumerate objects to a list or a tuple using the list() and tuple() methods, respectively.

Examples:

Ex 0: Documentation

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Equivalent to:

def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1

Ex 1: How enumerate() works in Python?
grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)

print(type(enumerateGrocery))

# converting to list
print(list(enumerateGrocery))

# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))

Output:

<class 'enumerate'>
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]

Ex 2: Looping over an enumerator object
grocery = ['bread', 'milk', 'butter']

for item in enumerate(grocery):
print(item)

print('\n')

for count, item in enumerate(grocery):
print(count, item)

print('\n')
# changing default start value
for count, item in enumerate(grocery, 100):
print(count, item)

Output:

(0, 'bread')
(1, 'milk')
(2, 'butter')

0 bread
1 milk
2 butter

100 bread
101 milk
102 butter


eval(expression[, globals[, locals]])

Description: The eval() method parses the expression passed to this method and runs python expression (code) within the program.

number = 9

# eval performs the multiplication passed as argument
square_number = eval('number * number')
print(square_number)

# Output: 81

The syntax of eval() is:

eval(expression, globals=None, locals=None)

The eval() function takes three parameters:

  • expression - the string parsed and evaluated as a Python expression
  • globals (optional) - a dictionary
  • locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.

The use of globals and locals will be discussed more below in the examples.

The eval() method returns the result evaluated from the expression.

Warnings when using eval(): Consider a situation where you are using a Unix-like system (macOS, Linux, etc) and you have imported the os module. The os module provides a portable way to use operating system functionalities like reading or writing to a file.

If you allow users to input a value using eval(input()), the user may issue commands to change the file or even delete all the files using the command os.system('rm -rf *').

If you are using eval(input()) in your code, it is a good idea to check which variables and methods the user can use. You can see which variables and methods are available using the dir() method.

from math import *
print(eval('dir()'))

Output:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

Restricting the use of available methods and variables in eval() via globals and locals parameters: More often than not, all the available methods and variables used in the expression (first parameter to eval()) may not be needed, or even may have a security hole. You may need to restrict the use of these methods and variables for eval(). You can do so by passing optional globals and locals parameters (dictionaries) to the eval() function.

  1. Both globals and locals parameters are omitted: If both parameters are omitted (as in our earlier examples), the expression is executed in the current scope. You can check the available variables and methods using following code: print(eval('dir()')

  2. Passing globals parameter; locals parameter is omitted: The globals and locals parameters (dictionaries) are used for global and local variables respectively. If the locals dictionary is omitted, it defaults to globals dictionary. Meaning, globals will be used for both global and local variables.

Note: You can check the current global and local dictionary in Python using globals() and locals() built-in methods respectively.

  1. Passing both globals and locals dictionaries: You can make needed functions and variables available for use by passing the locals dictionary. For example:
from math import *

a = 169
print(eval('sqrt(a)', {'__builtins__': None}, {'a': a, 'sqrt': sqrt}))

In this program, expression can have sqrt() method and variable a only. All other methods and variables are unavailable.

Restricting the use of eval() by passing globals and locals dictionaries will make your code secure particularly when you are using input provided by the user to the eval() method.

Note: Sometimes, eval() is not secure even with limited names. When an object and its methods are made accessible, almost anything can be done. The only secure way is by validating the user input.

Examples:

Ex 0: Documentation

The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.

The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

>>> x = 1
>>> eval('x+1')
2

This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()'s return value will be None.

Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().

See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.

Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.


Ex 1: How eval() works in Python
x = 1
print(eval('x + 1'))

Output:

2

Here, the eval() function evaluates the expression x + 1 and print is used to display this value.


Ex 2: Practical example to demonstrate use of eval()
# Perimeter of Square
def calculatePerimeter(l):
return 4*l

# Area of Square
def calculateArea(l):
return l*l

expression = input("Type a function: ")

for l in range(1, 5):
if (expression == 'calculatePerimeter(l)'):
print("If length is ", l, ", Perimeter = ", eval(expression))
elif (expression == 'calculateArea(l)'):
print("If length is ", l, ", Area = ", eval(expression))
else:
print('Wrong Function')
break

Output:

Type a function: calculateArea(l)
If length is 1 , Area = 1
If length is 2 , Area = 4
If length is 3 , Area = 9
If length is 4 , Area = 16

Ex 3: Passing empty dictionary as globals parameter
from math import *
print(eval('dir()', {}))

# The code will raise an exception
print(eval('sqrt(25)', {}))

Output:

['__builtins__']
Traceback (most recent call last):
File "<string>", line 5, in <module>
print(eval('sqrt(25)', {}))
File "<string>", line 1, in <module>
NameError: name 'sqrt' is not defined

If you pass an empty dictionary as globals, only the __builtins__ are available to expression (first parameter to the eval()).

Even though we have imported the math module in the above program, expression can't access any functions provided by the math module.


Ex 4: Making certain methods available
from math import *
print(eval('dir()', {'sqrt': sqrt, 'pow': pow}))
print(eval('sqrt(4)', { 'sqrt': sqrt }))

Output:

['__builtins__', 'pow', 'sqrt']
2.0

Here, the first expression can only use the sqrt() and the pow() methods along with __builtins__ while the second expression can only use the sqrt() method along with __builtins__.

It is also possible to change the name of the method available for the expression as you wish:

from math import *
names = {'square_root': sqrt, 'power': pow}
print(eval('dir()', names))

# Using square_root in Expression
print(eval('square_root(9)', names))

Output:

['__builtins__', 'power', 'square_root']
3.0

In the above program, square_root() calculates the square root using sqrt(). However, trying to use sqrt() directly will raise an error.


Ex 5: Restricting the use of built-ins

You can restrict the use of __builtins__ in the expression as follows:

eval(expression, {'__builtins__': None})


exec(object[, globals[, locals]])

Description: The exec() method executes the dynamically created program, which is either a string or a code object.

The syntax of exec():

exec(object, globals, locals)

exec() takes three parameters:

  • object - Either a string or a code object
  • globals (optional) - a dictionary
  • locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.

The use of globals and locals will be discussed throughout the examples.

exec() doesn't return any value, it returns None.

Be careful when using exec(): Consider a situation, you are using a Unix-like system (macOS, Linux etc) and you have imported the os module. The os module provides a portable way to use operating system functionalities like read or write a file.

If you allow users to input a value using exec(input()), the user may issue commands to change the file or even delete all the files using the command os.system('rm -rf *').

If you are using exec(input()) in your code, it's a good idea to check which variables and methods the user can use. You can see which variables and methods are available using the dir() method.

from math import *
exec('print(dir())')

Output:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

Restricting the use of available methods and variables in exec() via globals and locals parameters: More often than not, all the available methods and variables used in exec() may not be needed, or even may have a security hole. You can restrict the use of these variables and methods by passing optional globals and locals parameters (dictionaries) to the exec() method.

  1. Both globals and locals parameters are omitted: If both parameters are omitted (as in our earlier examples), the code expected to be executed by exec() is executed in the current scope. You can check the available variables and methods using the following code: exec('print(dir())')

  2. Passing globals parameter; locals parameter is omitted: The globals and locals parameters (dictionaries) are used for global and local variables respectively. If the locals dictionary is omitted, it defaults to globals dictionary. Meaning, globals will be used for both global and local variables.

Note: You can check the current global and local dictionary in Python using globals() and locals() built-in methods respectively.

  1. Passing empty dictionary as globals parameter:
from math import *
exec('print(dir())', {})

# This code will raise an exception
# exec('print(sqrt(9))', {})

Output:

['__builtins__']

If you pass an empty dictionary as globals, only the __builtins__ are available to the object (first parameter to exec()). Even though we have imported the math module in the above program, trying to access any of the functions provided by the math module will raise an exception.

Making certain methods available:

from math import *
exec('print(dir())', {'sqrt': sqrt, 'pow': pow})

# object can have sqrt() module
exec('print(sqrt(9))', {'sqrt': sqrt, 'pow': pow})

Here, the code that is executed by exec() can also have sqrt() and pow() methods along with __builtins__.

It's possible to change the name of the method as you wish:

from math import *
exec('print(dir())', {'squareRoot': sqrt, 'pow': pow})

# object can have squareRoot() module
exec('print(squareRoot(9))', {'squareRoot': sqrt, 'pow': pow})

In the above program, squareRoot() calculates the square root (similar functionality like sqrt()). However, trying to use sqrt() will raise an exception.

Restricting the use of built-ins: You can restrict the use of __builtins__ by giving value None to the '__builtins__' in the globals dictionary:

exec(object, {'__builtins__': None}) 
  1. Passing both globals and locals dictionaries: You can make needed functions and variables available for use by passing the locals dictionary. For example:
from math import *

globalsParameter = {'__builtins__' : None}
localsParameter = {'print': print, 'dir': dir}
exec('print(dir())', globalsParameter, localsParameter)

Output:

['dir', 'print']

Here, only two built-in methods print() and dir() can be executed by exec() method.

It's important to note that, exec() executes the code and doesn't return any value (returns None). Hence, you cannot use return and yield statements outside of the function definitions.

Examples:

Ex 0: Documentation

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [Note that the parser only accepts the Unix-style end of line convention. If you are reading the code from a file, make sure to use newline conversion mode to convert Windows or Mac-style newlines.] If it is a code object, it is simply executed. In all cases, the code that's executed is expected to be valid as file input (see the section "File input" in the Reference Manual). Be aware that the nonlocal, yield, and return statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

If the globals dictionary does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec().

Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.

Note: The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec().

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.


Ex 1: How exec() works?
program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)

Output:

Sum = 15

Here, the string object program is passed to exec() which executes the program. globals and locals are omitted in this case.


Ex 2: Allow user to provide input
program = input('Enter a program:')
exec(program)

Output:

Enter a program: [print(item) for item in [1, 2, 3]]
1
2
3

If you want to take Python code from the user which allows multiline code (using '\n'), you can use the compile() method before using exec().



filter(function, iterable)

Description: tbd

Examples:

Ex 0: Documentation

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.



float([x])

Description: tbd

Examples:

Ex 0: Documentation

Return a floating point number constructed from a number or string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:

sign           ::=  "+" | "-"infinity       ::=  "Infinity" | "inf"nan            ::=  "nan"numeric_value  ::=  floatnumber | infinity | nannumeric_string ::=  [sign] numeric_value

Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. Case is not significant, so, for example, "inf", "Inf", "INFINITY" and "iNfINity" are all acceptable spellings for positive infinity.

Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python's floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.

For a general Python object x, float(x) delegates to x.__float__(). If __float__() is not defined then it falls back to __index__().

If no argument is given, 0.0 is returned.

Examples:

>>> float('+1.23')
1.23
>>> float(' -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

The float type is described in Numeric Types — int, float, complex.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.7: x is now a positional-only parameter.

Changed in version 3.8: Falls back to __index__() if __float__() is not defined.



format(value[, format_spec])

Description: tbd

Examples:

Ex 0: Documentation

Convert a value to a "formatted" representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

The default format_spec is an empty string which usually gives the same effect as calling str(value).

A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value's __format__() method. A TypeError exception is raised if the method search reaches object and the format_spec is non-empty, or if either the format_spec or the return value are not strings.

Changed in version 3.4: object().__format__(format_spec) raises TypeError if format_spec is not an empty string.



frozenset([iterable])

Description: tbd

Examples:

Ex 0: Documentation

Return a new frozenset object, optionally with elements taken from iterable. frozenset is a built-in class. See frozenset and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in set, list, tuple, and dict classes, as well as the collections module.



getattr(object, name[, default])

Description: tbd

Examples:

Ex 0: Documentation

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Note: Since private name mangling happens at compilation time, one must manually mangle a private attribute's (attributes with two leading underscores) name in order to retrieve it with getattr().



globals()

Description: tbd

Examples:

Ex 0: Documentation

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).



hasattr(object, name)

Description: tbd

Examples:

Ex 0: Documentation

The arguments are an object and a string. The result is True if the string is the name of one of the object's attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)



hash(object)

Description: tbd

Examples:

Ex 0: Documentation

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

Note: For objects with custom __hash__() methods, note that hash() truncates the return value based on the bit width of the host machine. See __hash__() for details.



help([object])

Description: tbd

Examples:

Ex 0: Documentation

Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function, when invoking help(), it means that the parameters prior to the slash are positional-only. For more info, see the FAQ entry on positional-only parameters.

This function is added to the built-in namespace by the site module.

Changed in version 3.4: Changes to pydoc and inspect mean that the reported signatures for callables are now more comprehensive and consistent.



hex(x)

Description: tbd

Examples:

Ex 0: Documentation

Convert an integer number to a lowercase hexadecimal string prefixed with "0x". If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'

If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:

>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')

See also format() for more information.

See also int() for converting a hexadecimal string to an integer using a base of 16.

Note: To obtain a hexadecimal string representation for a float, use the float.hex() method.



id(object)

Description: tbd

Examples:

Ex 0: Documentation

Return the "identity" of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

Raises an auditing event builtins.id with argument id.



input([prompt])

Description: tbd

Examples:

Ex 0: Documentation

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Raises an auditing event builtins.input with argument prompt before reading input

Raises an auditing event builtins.input/result with the result after successfully reading input.



int([x]); int(x, base=10)

Description: tbd

Examples:

Ex 0: Documentation

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __index__(), it returns x.__index__(). If x defines __trunc__(), it returns x.__trunc__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).

The integer type is described in Numeric Types — int, float, complex.

Changed in version 3.4: If base is not an instance of int and the base object has a base.__index__ method, that method is called to obtain an integer for the base. Previous versions used base.__int__ instead of base.__index__.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.7: x is now a positional-only parameter.

Changed in version 3.8: Falls back to __index__() if __int__() is not defined.



isinstance(object, classinfo)

Description: tbd

Examples:

Ex 0: Documentation

Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples), return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.



issubclass(class, classinfo)

Description: tbd

Examples:

Ex 0: Documentation

Return True if class is a subclass (direct, indirect or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.



iter(object[, sentinel])

Description: tbd

Examples:

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

See also Iterator Types.

One useful application of the second form of iter() is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:

from functools import partial
with open('mydata.db', 'rb') as f:
for block in iter(partial(f.read, 64), b''):
process_block(block)

len(s)

Description: tbd

Examples:

Ex 0: Documentation

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

CPython implementation detail: len raises OverflowError on lengths larger than sys.maxsize, such as range(2 ** 100).



list([iterable])

Description: tbd

Examples:

Ex 0: Documentation

Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.



locals()

Description: tbd

Examples:

Ex 0: Documentation

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.



map(function, iterable, ...)

Description: tbd

Examples:

Ex 0: Documentation

Return an iterator that applies function to every item of iterable (e.g., a string, list, tuple, dict, etc.), yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().


Ex 1: Basic illustration of usage

The code block

nums = [1,2,3]

def non_lambda(num):
return num ** 2

my_nonlambda_iterator = map(non_lambda, nums)
my_lambda_iterator = map(lambda x: x**2, nums)

print(my_lambda_iterator)
print(next(my_lambda_iterator))
print(next(my_lambda_iterator))
print(next(my_lambda_iterator))

print(my_nonlambda_iterator)
print(list(my_nonlambda_iterator))

has the following output:

<map object at 0x10753bdf0>
1
4
9
<map object at 0x10753be80>
[1, 4, 9]

This illustrates that the map function returns an iterator which can be unpacked all at once by means of something like list or can be iterated through by means of the built-in next function.

As noted in the description for map, this function can take multiple iterables--the iterator stops when the shortest iterable is exhausted.

For example, the code block above can be adjusted to

nums1 = [1,2,3]
nums2 = [4,5,6,7]
nums3 = [8,9,10,11,12]

def non_lambda(num1, num2, num3):
return num1 + num2 + num3

my_nonlambda_iterator = map(non_lambda, nums1, nums2, nums3)
my_lambda_iterator = map(lambda x,y,z: x+y+z, nums1, nums2, nums3)

print(my_lambda_iterator)
print(next(my_lambda_iterator))
print(next(my_lambda_iterator))
print(next(my_lambda_iterator))

print(my_nonlambda_iterator)
print(list(my_nonlambda_iterator))

which will yield the output

<map object at 0x10fbcddf0>
13
16
19
<map object at 0x10fbcdf10>
[13, 16, 19]

In this case, nums1 = [1,2,3] is the shortest iterable.


Ex 2: Converting map object to set
def calculateSquare(n):
return n*n


numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

yields

<map object at 0x7f722da129e8>
{16, 1, 4, 9}

Each item of the tuple is squared.


Ex 3: Using a lambda function with map

Since map expects a function to be passed in, lambda functions are commonly used while working with map. A lambda function is a short function without a name (similar to anonymous functions () => {} in JavaScript; the main difference is that lambda functions need to be one-liners in Python).

The code block

numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

yields as its output:

<map 0x7fafc21ccb00>
{16, 1, 4, 9}

There is no real difference from this example to the one previous.


Ex 4: Passing multiple iterables to map and using lambda

We can add corresponding items of two lists:

num1 = [4, 5, 6]
num2 = [5, 6, 7]

result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))

This yields:

[9, 11, 13]

Ex 5: Number to sum of its numerals (Edabit challenge)

From this challenge we see that a number is said to be Harshad if it is exactly divisible by the sum of its digits. Create a function that determines whether a number is Harshad or not.

is_harshad(75) ➞ False
# 7 + 5 = 12
# 75 is not exactly divisible by 12

is_harshad(171) ➞ True
# 1 + 7 + 1 = 9
# 9 exactly divides 171

is_harshad(481) ➞ True

is_harshad(89) ➞ False

is_harshad(516) ➞ True

is_harshad(200) ➞ True

The map function can be used to our advantage here:

def is_harshad(n):
S = sum(map(int, str(n)))
return n % S == 0

By itself, n is not iterable. But strings are iterable. Hence, str(n) gives us an iterable string whose characters are the numerals that make up n. We can use the map function to apply the int function to each character in str(n) to yield an iterator upon which sum can act.



max(iterable, *[, key, default]); max(arg1, arg2, *args[, key])

Description: tbd

Examples:

Ex 0: Documentation

Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).

New in version 3.4: The default keyword-only argument.

Changed in version 3.8: The key can be None.



memoryview(object)

Description: tbd

Examples:

Ex 0: Documentation

Return a "memory view" object created from the given argument. See Memory Views for more information.



min(iterable, *[, key, default]); min(arg1, arg2, *args[, key])

Description: tbd

Examples:

Ex 0: Documentation

Return the smallest item in an iterable or the smallest of two or more arguments.

If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0] and heapq.nsmallest(1, iterable, key=keyfunc).

New in version 3.4: The default keyword-only argument.

Changed in version 3.8: The key can be None.



next(iterator[, default])

Description: tbd

Examples:

Ex 0: Documentation

Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.



object()

Description: tbd

Examples:

Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.

Note: object does not have a __dict__, so you can't assign arbitrary attributes to an instance of the object class.


oct(x)

Description: tbd

Examples:

Ex 0: Documentation

Convert an integer number to an octal string prefixed with "0o". The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. For example:

>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'

If you want to convert an integer number to octal string either with prefix "0o" or not, you can use either of the following ways.

>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')

See also format() for more information.


Ascii Table:

ASCII Table
DecHexOctBinaryHTMLCharDescription
00000000000000&#0;NULNull
10100100000001&#1;SOHStart of Header
20200200000010&#2;STXStart of Text
30300300000011&#3;ETXEnd of Text
40400400000100&#4;EOTEnd of Transmission
50500500000101&#5;ENQEnquiry
60600600000110&#6;ACKAcknowledge
70700700000111&#7;BELBell
80801000001000&#8;BSBackspace
90901100001001&#9;HTHorizontal Tab
100A01200001010&#10;LFLine Feed
110B01300001011&#11;VTVertical Tab
120C01400001100&#12;FFForm Feed
130D01500001101&#13;CRCarriage Return
140E01600001110&#14;SOShift Out
150F01700001111&#15;SIShift In
161002000010000&#16;DLEData Link Escape
171102100010001&#17;DC1Device Control 1
181202200010010&#18;DC2Device Control 2
191302300010011&#19;DC3Device Control 3
201402400010100&#20;DC4Device Control 4
211502500010101&#21;NAKNegative Acknowledge
221602600010110&#22;SYNSynchronize
231702700010111&#23;ETBEnd of Transmission Block
241803000011000&#24;CANCancel
251903100011001&#25;EMEnd of Medium
261A03200011010&#26;SUBSubstitute
271B03300011011&#27;ESCEscape
281C03400011100&#28;FSFile Separator
291D03500011101&#29;GSGroup Separator
301E03600011110&#30;RSRecord Separator
311F03700011111&#31;USUnit Separator
322004000100000&#32;spaceSpace
332104100100001&#33;!exclamation mark
342204200100010&#34;"double quote
352304300100011&#35;#number
362404400100100&#36;$dollar
372504500100101&#37;%percent
382604600100110&#38;&ampersand
392704700100111&#39;'single quote
402805000101000&#40;(left parenthesis
412905100101001&#41;)right parenthesis
422A05200101010&#42;*asterisk
432B05300101011&#43;+plus
442C05400101100&#44;,comma
452D05500101101&#45;-minus
462E05600101110&#46;.period
472F05700101111&#47;/slash
483006000110000&#48;0zero
493106100110001&#49;1one
503206200110010&#50;2two
513306300110011&#51;3three
523406400110100&#52;4four
533506500110101&#53;5five
543606600110110&#54;6six
553706700110111&#55;7seven
563807000111000&#56;8eight
573907100111001&#57;9nine
583A07200111010&#58;:colon
593B07300111011&#59;;
603C07400111100&#60;<less than
613D07500111101&#61;=equality sign
623E07600111110&#62;>greater than
633F07700111111&#63;?question mark
644010001000000&#64;@at sign
654110101000001&#65;A
664210201000010&#66;B
674310301000011&#67;C
684410401000100&#68;D
694510501000101&#69;E
704610601000110&#70;F
714710701000111&#71;G
724811001001000&#72;H
734911101001001&#73;I
744A11201001010&#74;J
754B11301001011&#75;K
764C11401001100&#76;L
774D11501001101&#77;M
784E11601001110&#78;N
794F11701001111&#79;O
805012001010000&#80;P
815112101010001&#81;Q
825212201010010&#82;R
835312301010011&#83;S
845412401010100&#84;T
855512501010101&#85;U
865612601010110&#86;V
875712701010111&#87;W
885813001011000&#88;X
895913101011001&#89;Y
905A13201011010&#90;Z
915B13301011011&#91;[left square bracket
925C13401011100&#92;\backslash
935D13501011101&#93;]right square bracket
945E13601011110&#94;^caret / circumflex
955F13701011111&#95;_underscore
966014001100000&#96;`grave / accent
976114101100001&#97;a
986214201100010&#98;b
996314301100011&#99;c
1006414401100100&#100;d
1016514501100101&#101;e
1026614601100110&#102;f
1036714701100111&#103;g
1046815001101000&#104;h
1056915101101001&#105;i
1066A15201101010&#106;j
1076B15301101011&#107;k
1086C15401101100&#108;l
1096D15501101101&#109;m
1106E15601101110&#110;n
1116F15701101111&#111;o
1127016001110000&#112;p
1137116101110001&#113;q
1147216201110010&#114;r
1157316301110011&#115;s
1167416401110100&#116;t
1177516501110101&#117;u
1187616601110110&#118;v
1197716701110111&#119;w
1207817001111000&#120;x
1217917101111001&#121;y
1227A17201111010&#122;z
1237B17301111011&#123;{left curly bracket
1247C17401111100&#124;|vertical bar
1257D17501111101&#125;}right curly bracket
1267E17601111110&#126;~tilde
1277F17701111111&#127;DELdelete

Extended ASCII Table
DecHexBinaryHTMLChar
1288010000000-€
1298110000001-
1308210000010-‚
1318310000011-ƒ
1328410000100-„
1338510000101-…
1348610000110-†
1358710000111-‡
1368810001000-ˆ
1378910001001-‰
1388A10001010-Š
1398B10001011-‹
1408C10001100-Œ
1418D10001101-
1428E10001110-Ž
1438F10001111-
1449010010000-
1459110010001-‘
1469210010010-’
1479310010011-“
1489410010100-”
1499510010101-•
1509610010110-–
1519710010111-—
1529810011000-˜
1539910011001-™
1549A10011010-š
1559B10011011-›
1569C10011100-œ
1579D10011101-
1589E10011110-ž
1599F10011111-Ÿ
160A010100000&#160;
161A110100001&#161;¡
162A210100010&#162;¢
163A310100011&#163;£
164A410100100&#164;¤
165A510100101&#165;¥
166A610100110&#166;¦
167A710100111&#167;§
168A810101000&#168;¨
169A910101001&#169;©
170AA10101010&#170;ª
171AB10101011&#171;«
172AC10101100&#172;¬
173AD10101101&#173;­
174AE10101110&#174;®
175AF10101111&#175;¯
176B010110000&#176;°
177B110110001&#177;±
178B210110010&#178;²
179B310110011&#179;³
180B410110100&#180;´
181B510110101&#181;µ
182B610110110&#182;
183B710110111&#183;·
184B810111000&#184;¸
185B910111001&#185;¹
186BA10111010&#186;º
187BB10111011&#187;»
188BC10111100&#188;¼
189BD10111101&#189;½
190BE10111110&#190;¾
191BF10111111&#191;¿
192C011000000&#192;À
193C111000001&#193;Á
194C211000010&#194;Â
195C311000011&#195;Ã
196C411000100&#196;Ä
197C511000101&#197;Å
198C611000110&#198;Æ
199C711000111&#199;Ç
200C811001000&#200;È
201C911001001&#201;É
202CA11001010&#202;Ê
203CB11001011&#203;Ë
204CC11001100&#204;Ì
205CD11001101&#205;Í
206CE11001110&#206;Î
207CF11001111&#207;Ï
208D011010000&#208;Ð
209D111010001&#209;Ñ
210D211010010&#210;Ò
211D311010011&#211;Ó
212D411010100&#212;Ô
213D511010101&#213;Õ
214D611010110&#214;Ö
215D711010111&#215;×
216D811011000&#216;Ø
217D911011001&#217;Ù
218DA11011010&#218;Ú
219DB11011011&#219;Û
220DC11011100&#220;Ü
221DD11011101&#221;Ý
222DE11011110&#222;Þ
223DF11011111&#223;ß
224E011100000&#224;à
225E111100001&#225;á
226E211100010&#226;â
227E311100011&#227;ã
228E411100100&#228;ä
229E511100101&#229;å
230E611100110&#230;æ
231E711100111&#231;ç
232E811101000&#232;è
233E911101001&#233;é
234EA11101010&#234;ê
235EB11101011&#235;ë
236EC11101100&#236;ì
237ED11101101&#237;í
238EE11101110&#238;î
239EF11101111&#239;ï
240F011110000&#240;ð
241F111110001&#241;ñ
242F211110010&#242;ò
243F311110011&#243;ó
244F411110100&#244;ô
245F511110101&#245;õ
246F611110110&#246;ö
247F711110111&#247;÷
248F811111000&#248;ø
249F911111001&#249;ù
250FA11111010&#250;ú
251FB11111011&#251;û
252FC11111100&#252;ü
253FD11111101&#253;ý
254FE11111110&#254;þ
255FF11111111&#255;ÿ


open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Description: tbd

Examples:

Ex 0: Documentation

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised. See Reading and Writing Files for more examples of how to use this function.

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

CharacterMeaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open for updating (reading and writing)

The default mode is 'r' (open for reading text, synonym of 'rt'). Modes 'w+' and 'w+b' open and truncate the file. Modes 'r+' and 'r+b' open the file with no truncation.

As mentioned in the Overview, Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

There is an additional mode character permitted, 'U', which no longer has any effect, and is considered deprecated. It previously enabled universal newlines in text mode, which became the default behaviour in Python 3.0. Refer to the documentation of the newline parameter for further details.

Note: Python doesn't depend on the underlying operating system's notion of text files; all the processing is done by Python itself, and is therefore platform-independent.

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

  • Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.
  • "Interactive" text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers), though any error handling name that has been registered with codecs.register_error() is also valid. The standard names include:

  • 'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect.
  • 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.
  • 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data.
  • 'surrogateescape' will represent any incorrect bytes as low surrogate code units ranging from U+DC80 to U+DCFF. These surrogate code units will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.
  • 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;.
  • 'backslashreplace' replaces malformed data by Python's backslashed escape sequences.
  • 'namereplace' (also only supported when writing) replaces unsupported characters with \N{...} escape sequences.

newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

  • When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
  • When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be True (the default) otherwise an error will be raised.

A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open() as opener results in functionality similar to passing None).

The newly created file is non-inheritable.

The following example uses the dir_fd parameter of the os.open() function to open a file relative to a given directory:

>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
... return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
... print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd) # don't leak a file descriptor

The type of file object returned by the open() function depends on the mode. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a subclass of io.TextIOBase (specifically io.TextIOWrapper). When used to open a file in a binary mode with buffering, the returned class is a subclass of io.BufferedIOBase. The exact class varies: in read binary mode, it returns an io.BufferedReader; in write binary and append binary modes, it returns an io.BufferedWriter, and in read/write mode, it returns an io.BufferedRandom. When buffering is disabled, the raw stream, a subclass of io.RawIOBase, io.FileIO, is returned.

See also the file handling modules, such as, fileinput, io (where open() is declared), os, os.path, tempfile, and shutil.

Raises an auditing event open with arguments file, mode, flags.

The mode and flags arguments may have been modified or inferred from the original call.

Changed in version 3.3:

  • The opener parameter was added.
  • The 'x' mode was added.
  • IOError used to be raised, it is now an alias of OSError.
  • FileExistsError is now raised if the file opened in exclusive creation mode ('x') already exists.

Changed in version 3.4:

  • The file is now non-inheritable.

Deprecated since version 3.4, will be removed in version 3.10: The 'U' mode.

Changed in version 3.5:

  • If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).
  • The 'namereplace' error handler was added.

Changed in version 3.6:



ord(c)

Description: tbd

Examples:

Ex 0: Documentation

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().


Ascii Table:

ASCII Table
DecHexOctBinaryHTMLCharDescription
00000000000000&#0;NULNull
10100100000001&#1;SOHStart of Header
20200200000010&#2;STXStart of Text
30300300000011&#3;ETXEnd of Text
40400400000100&#4;EOTEnd of Transmission
50500500000101&#5;ENQEnquiry
60600600000110&#6;ACKAcknowledge
70700700000111&#7;BELBell
80801000001000&#8;BSBackspace
90901100001001&#9;HTHorizontal Tab
100A01200001010&#10;LFLine Feed
110B01300001011&#11;VTVertical Tab
120C01400001100&#12;FFForm Feed
130D01500001101&#13;CRCarriage Return
140E01600001110&#14;SOShift Out
150F01700001111&#15;SIShift In
161002000010000&#16;DLEData Link Escape
171102100010001&#17;DC1Device Control 1
181202200010010&#18;DC2Device Control 2
191302300010011&#19;DC3Device Control 3
201402400010100&#20;DC4Device Control 4
211502500010101&#21;NAKNegative Acknowledge
221602600010110&#22;SYNSynchronize
231702700010111&#23;ETBEnd of Transmission Block
241803000011000&#24;CANCancel
251903100011001&#25;EMEnd of Medium
261A03200011010&#26;SUBSubstitute
271B03300011011&#27;ESCEscape
281C03400011100&#28;FSFile Separator
291D03500011101&#29;GSGroup Separator
301E03600011110&#30;RSRecord Separator
311F03700011111&#31;USUnit Separator
322004000100000&#32;spaceSpace
332104100100001&#33;!exclamation mark
342204200100010&#34;"double quote
352304300100011&#35;#number
362404400100100&#36;$dollar
372504500100101&#37;%percent
382604600100110&#38;&ampersand
392704700100111&#39;'single quote
402805000101000&#40;(left parenthesis
412905100101001&#41;)right parenthesis
422A05200101010&#42;*asterisk
432B05300101011&#43;+plus
442C05400101100&#44;,comma
452D05500101101&#45;-minus
462E05600101110&#46;.period
472F05700101111&#47;/slash
483006000110000&#48;0zero
493106100110001&#49;1one
503206200110010&#50;2two
513306300110011&#51;3three
523406400110100&#52;4four
533506500110101&#53;5five
543606600110110&#54;6six
553706700110111&#55;7seven
563807000111000&#56;8eight
573907100111001&#57;9nine
583A07200111010&#58;:colon
593B07300111011&#59;;
603C07400111100&#60;<less than
613D07500111101&#61;=equality sign
623E07600111110&#62;>greater than
633F07700111111&#63;?question mark
644010001000000&#64;@at sign
654110101000001&#65;A
664210201000010&#66;B
674310301000011&#67;C
684410401000100&#68;D
694510501000101&#69;E
704610601000110&#70;F
714710701000111&#71;G
724811001001000&#72;H
734911101001001&#73;I
744A11201001010&#74;J
754B11301001011&#75;K
764C11401001100&#76;L
774D11501001101&#77;M
784E11601001110&#78;N
794F11701001111&#79;O
805012001010000&#80;P
815112101010001&#81;Q
825212201010010&#82;R
835312301010011&#83;S
845412401010100&#84;T
855512501010101&#85;U
865612601010110&#86;V
875712701010111&#87;W
885813001011000&#88;X
895913101011001&#89;Y
905A13201011010&#90;Z
915B13301011011&#91;[left square bracket
925C13401011100&#92;\backslash
935D13501011101&#93;]right square bracket
945E13601011110&#94;^caret / circumflex
955F13701011111&#95;_underscore
966014001100000&#96;`grave / accent
976114101100001&#97;a
986214201100010&#98;b
996314301100011&#99;c
1006414401100100&#100;d
1016514501100101&#101;e
1026614601100110&#102;f
1036714701100111&#103;g
1046815001101000&#104;h
1056915101101001&#105;i
1066A15201101010&#106;j
1076B15301101011&#107;k
1086C15401101100&#108;l
1096D15501101101&#109;m
1106E15601101110&#110;n
1116F15701101111&#111;o
1127016001110000&#112;p
1137116101110001&#113;q
1147216201110010&#114;r
1157316301110011&#115;s
1167416401110100&#116;t
1177516501110101&#117;u
1187616601110110&#118;v
1197716701110111&#119;w
1207817001111000&#120;x
1217917101111001&#121;y
1227A17201111010&#122;z
1237B17301111011&#123;{left curly bracket
1247C17401111100&#124;|vertical bar
1257D17501111101&#125;}right curly bracket
1267E17601111110&#126;~tilde
1277F17701111111&#127;DELdelete

Extended ASCII Table
DecHexBinaryHTMLChar
1288010000000-€
1298110000001-
1308210000010-‚
1318310000011-ƒ
1328410000100-„
1338510000101-…
1348610000110-†
1358710000111-‡
1368810001000-ˆ
1378910001001-‰
1388A10001010-Š
1398B10001011-‹
1408C10001100-Œ
1418D10001101-
1428E10001110-Ž
1438F10001111-
1449010010000-
1459110010001-‘
1469210010010-’
1479310010011-“
1489410010100-”
1499510010101-•
1509610010110-–
1519710010111-—
1529810011000-˜
1539910011001-™
1549A10011010-š
1559B10011011-›
1569C10011100-œ
1579D10011101-
1589E10011110-ž
1599F10011111-Ÿ
160A010100000&#160;
161A110100001&#161;¡
162A210100010&#162;¢
163A310100011&#163;£
164A410100100&#164;¤
165A510100101&#165;¥
166A610100110&#166;¦
167A710100111&#167;§
168A810101000&#168;¨
169A910101001&#169;©
170AA10101010&#170;ª
171AB10101011&#171;«
172AC10101100&#172;¬
173AD10101101&#173;­
174AE10101110&#174;®
175AF10101111&#175;¯
176B010110000&#176;°
177B110110001&#177;±
178B210110010&#178;²
179B310110011&#179;³
180B410110100&#180;´
181B510110101&#181;µ
182B610110110&#182;
183B710110111&#183;·
184B810111000&#184;¸
185B910111001&#185;¹
186BA10111010&#186;º
187BB10111011&#187;»
188BC10111100&#188;¼
189BD10111101&#189;½
190BE10111110&#190;¾
191BF10111111&#191;¿
192C011000000&#192;À
193C111000001&#193;Á
194C21100