Aman Ai Primers Python
Aman Ai Primers Python
Back to aman.ai
search...
Primers • Python
Python
Python Versions
Python Style Guide
Python Notebooks: Jupyter and Colab
The Zen of Python
Indentation
Code Comments
Variables
Print Function
Input Function
Order of Operations
Basic Data Types
Numbers
Use Underscores to Format Large Numbers
Booleans
Strings
String Formatting
Old Style/pre-Python 2.6
New Style/Python 2.6
F-strings
Padding and Aligning Strings
Truncating Long Strings
Combining Truncating and Padding
Numbers
Padding Numbers
Index of a Substring in a Python String
Replace One String with Another String Using Regular Expressions
Containers
Lists
Iterate Over a List
List Comprehensions
From Loops to Comprehensions
Nested Loops
Slicing
List Functions
Dictionaries
Accessing a Non-existent Key
<dict>.get()
defaultdict
Key Membership Check
Iterating Over Keys
del
Key Datatypes
Iterate Over a Dictionary
Dictionary Comprehensions
Sets
Set Operations
Iterating Over a Set
Set Comprehensions
Tuples
Type Hinting
Type Aliases
Any
Tuple
List
Union
Optional
Control Flow
if Statement
Conditional Expression
for Loop
else Clause
ISD Moldova - Eastern Europe Outsourcing
while Loop OPENEN
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
Lambda Functions
soft.com
Lambda Function Use-cases
The Pros and Cons of Lambda Functions
Misuse and Overuse Scenarios
Misuse: Naming Lambda Expressions
Misuse: Needless Function Calls
Overuse: Simple, but Non-trivial Functions
Overuse: When Multiple Lines Would Help
Overuse: Lambda with Map and Filter
Misuse: Sometimes You Don’t Even Need to Pass a Function
Overuse: Using Lambda for Very Simple Operations
Overuse: When Higher Order Functions Add Confusion
The Iterator Protocol: How for Loops Work in Python
Looping with Indexes
Iterables
Iterators
Iterators are Also Iterables
The Iterator Protocol
Looping with Iterators
Putting It All Together
Creating a Custom Iterator
Why Make an Iterator?
Making an Iterator: the Object-oriented Way
Generators
Generator Functions
Generator Expressions
Generator Expressions vs. Generator Functions
Decorators
Functions
Nested Functions
Defining a Nonlocal Variable in a Nested Function Using nonlocal
Closure
Defining a Global Variable Using global
File I/O
Files
Opening Files in Python
Closing Files in Python
Writing to Files in Python
Reading Files in Python
read()
for Loop
readline()
readlines()
Python File Methods
Magic Methods
Common Magic Methods
Construction and Initialization
Comparison Magic Methods
Numeric Magic Methods
Unary Operators and Functions
Normal Arithmetic Operators
Creating Custom Sequences
Requirements
The Magic Behind Containers
Example
Making Operators Work on Custom Classes
Common Magic Methods Scenarios
Exceptions
Exception Handling
Multiple except Clauses
Custom Exceptions
Clean-up Actions ( try … finally )
Combining try , except and finally
Handle Exceptions with a try/except Block
else Clause
with Statement
Handling Nested Exceptions
Built-in Exceptions
Modules
Modules vs. Packages
Classes
Inheritance
ISD Moldova - Eastern Europe Outsourcing
Multiple Inheritance
Selected Built-ins OPENEN
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
soft.com any / all
dir
eval
filter
isinstance
issubclass
iter
len
range
reversed
sort
Basics
Sort Key
zip
References
Further Reading
Citation
Open in Colab
Python
Python is a high-level, dynamically typed multiparadigm programming language, created by Guido van
Rossum in the early 90s. It is now one of the most popular languages in existence.
Python’s syntactic clarity allows you to express very powerful ideas in very few lines of code while being very
readable. It’s basically executable pseudocode!
As an example, here is an implementation of the classic Quicksort algorithm in Python:
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
Note: This primer applies to Python 3 specifically. Check out the Python 2 primer if you want to learn about the (now
old) Python 2.7.
Python Versions
As of Janurary 1, 2020, Python has officially dropped support for Python 2.
If you haven’t experimented with Python at all and are just starting off, we recommend you begin with the
latest version of Python 3.
You can double-check your Python version at the command line after activating your environment by running
python --version .
which outputs:
Readability counts.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
For more on the coding principles above, refer to The Zen of Python, Explained.
Indentation
Python is big on indentation! Where in other programming languages the indentation in code is to improve
readability, Python uses indentation to indicate a block of code.
The convention is to use four spaces, not tabs.
Code Comments
Python supports two types of comments: single-line and multi-line, as detailed below:
They are also the closest concept to multi-line comments in other languages.
"""
Variables
In Python, there are no declarations unlike C/C++; only assignments:
some_var = 5
some_var # Returns 5
Variables are “names” in Python that simply refer to objects. This implies that you can make another variable
point to an object by assigning it the original variable that was pointing to the same object.
b += [4] # Extend the list pointed by "a" and "b" by adding "4" to it
is checks if two variables refer to the same object, while == checks if the objects that the variables point
to have the same values:
OPENEN
b is a teams of Java#and
Outsourcing services provided by dedicated Returns True, "a"
.NET developers. isd-and "b" refer to the *same* object
soft.com b == a # Returns True, the objects that "a" and "b" are pointing to are *equal
b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4]
b is a # Returns False, "a" and "b" do not refer to the *same* object
b == a # Returns True, the objects that "a" and "b" are pointing to are *equal
In Python, everything is an object. This means that even None (which is used to denote that the variable
doesn’t point to an object yet) is also an object!
Python has local and global variables. Here’s an example of local vs. global variable scope:
x = 5
def set_x(num):
# Local var x not the same as global variable x
x = num # Returns 43
x # Returns 43
def set_global_x(num):
global x
x # Returns 5
x # Returns 6
set_x(43)
set_global_x(6)
Print Function
Python has a print function:
print("I'm Python. Nice to meet you!") # Returns I'm Python. Nice to meet you!
By default, the print function also prints out a newline at the end. Override the optional argument end to
modify this behavior:
Input Function
Python offers a simple way to get input data from console:
Order of Operations
Just like mathematical operations in other languages, Python uses the BODMAS rule (also called the
PEMDAS rule) to ascertain operator precedence. BODMAS is an acronym and it stands for Bracket, Of,
Division, Multiplication, Addition, and Subtraction.
1 + 3 * 2 # Returns 7
(1 + 3) * 2 # Returns 8
x += 1 # Returns "4"
x *= 2 # Returns "8"
y = 2.5
type(y) # Returns "<class 'float'>"
Some nuances in integer/float division that you should take note of:
# Integer division rounds down for both positive and negative numbers
-5 // 3 # -2
5.0 // 3.0 # 1.0
-5.0 // 3.0 # -2.0
Note that unlike many languages, Python does not have unary increment ( x++ ) or decrement ( x-- )
operators, but accepts the += and -= operators.
Python also has built-in types for complex numbers; you can find all of the details in the Python
documentation.
When working with a large number in Python, it can be difficult to figure out how many digits that number
has. Python 3.6 and above allows you to use underscores as visual separators to group digits.
In the example below, underscores are used to group decimal numbers by thousands.
large_num = 1_000_000
large_num # Returns 1000000
Booleans
Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols
( && , || , etc.):
t = True
f = False
type(t) # Returns "<class 'bool'>"
True * 8 # Returns 8
False - 5 # Returns -5
None , 0 , and empty strings/lists/dicts/tuples all evaluate to False . All other values are True .
soft.com
bool([]) # Returns False
# Equality is ==
1 == 1 # Returns True
2 == 1 # Returns False
# Inequality is !=
1 != 1 # Returns False
2 != 1 # Returns True
# More comparisons
Casting integers as booleans transforms a non-zero integer to True , while zeros get transformed to
False :
Using logical operators with integers casts them to booleans for evaluation, using the same rules as
mentioned above. However, note that the original pre-cast value is returned.
0 and 2 # Returns 0
-5 or 0 # Returns -5
Strings
Python has great support for strings:
# But note that you can nest one in another, for e.g.,
print(hello) # Prints "hello"
"hello " "world" # String literals (but not variables) can be concatenate
'%s %s %d' % (hello, world, 12) # sprintf style string formatting, returns "hello world
s = "hello"
s.capitalize() # Capitalize a string; returns "Hello"
# returns "he(ell)(ell)o"
' world '.strip() # Strip leading and trailing whitespace; returns "world"
You can find a list of all string methods in the Python documentation.
String Formatting
Python has several different ways of formatting strings. Simple positional formatting is probably the most
common use-case. Use it if the order of your arguments is not likely to change and you only have very few
Note that both the old and new style of formatting are still compatible with the newest releases of Python,
which is version 3.8 at the time of writing.
With the new style formatting, you can give placeholders an explicit positional index (called positional
arguments). This allows for re-arranging the order of display without changing the arguments. This operation
is not available with old-style formatting.
For the example print('{0} {1} cost ${2}'.format(6, 'bananas', 1.74)) , the output is 6
bananas cost $1.74 , as explained below:
You can also use keyword arguments instead of positional parameters to produce the same result. This is
called keyword arguments.
F-strings
Starting Python 3.6, you can also format strings using f-string literals, which are much more powerful than
the old/new string formatters we discussed earlier:
name = "Reiko"
f"She said her name is {name}." # Returns "She said her name is Reiko."
# You can basically put any Python statement inside the braces and it will be output in
f"{name} is {len(name)} characters long." # Returns "Reiko is 5 characters long."
By default, values are formatted to take up only as many characters as needed to represent the content. It is
however also possible to define that a value should be padded to a specific length.
Unfortunately the default alignment differs between old and new style formatting. The old style defaults to
right aligned while the new style is left aligned.
ISD Moldova - Eastern
To alignEurope
text right: Outsourcing
OPENEN
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
soft.com
'%10s' % ('test',) # Returns " test"
Again, the new style formatting surpasses the old variant by providing more control over how values are
padded and aligned. You are able to choose the padding character and override the default space character
for padding. This operation is not available with old-style formatting.
And also center align values. This operation is not available with old-style formatting.
When using center alignment where the length of the string leads to an uneven split of the padding
characters the extra character will be placed on the right side. This operation is not available with old-style
formatting.
You can also combine the field numbering (say, {0} for the first argument) specification with the format
type (say, {:s} for strings):
Unpacking arguments:
test2 = "test2"
test1 = "test1"
test0 = "test0"
s1 = 'a'
s2 = 'ab'
s3 = 'abc'
s4 = 'abcd'
print(f'{s1:>10}') # Prints a
print(f'{s2:>10}') # Prints ab
Inverse to padding it is also possible to truncate overly long values to a specific number of characters. The
number behind the . in the format specifies the precision of the output. For strings that means that the
output is truncated to the specified length. In our example this would be 5 characters.
OPENEN
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
soft.com
Combining Truncating and Padding
Numbers
Floats:
Padding Numbers
Again similar to truncating strings the precision for floating point numbers limits the number of positions
after the decimal point. For floating points, the padding value represents the length of the complete output
(including the decimal). In the example below we want our output to have at least 6 characters with 2 after
the decimal point.
For integer values providing a precision doesn’t make much sense and is actually forbidden in the new style
(it will result in a ValueError ).
Some examples:
Specify a sign for floats:
Show the sign always:
Show a space for positive numbers, but a sign for negative numbers:
Show a space for positive numbers, but a sign for negative numbers:
Converting the value to different bases using replacing {:d} , {:x} and {:o} :
Note that format also supports binary numbers:
With 0x , 0o , or 0b as prefix:
Expressing a percentage:
points = 19
total = 22
import datetime
# Returns:
# 'left<<<<<<<<<<<<'
# '^^^^^center^^^^^'
# '>>>>>>>>>>>right'
width = 5
# Prints:
# 5 5 5 101
# 6 6 6 110
# 7 7 7 111
# 8 8 10 1000
# 9 9 11 1001
# 10 A 12 1010
# 11 B 13 1011
val = 12.3
Format width:
# Prints:
# 01 1 1
# 02 4 8
# 03 9 27
# 04 16 64
# 05 25 125
# 06 36 216
# 07 49 343
# 08 64 512
# 09 81 729
# 10 100 1000
If you want to find the index of a substring in a string, use the str.find() method which returns the index
of the first occurrence of the substring if found and -1 otherwise.
sentence.find("day") # Returns 2
sentence.find("nice") # Returns -1
You can also provide the starting and stopping position of the search:
sentence.find("day", 3) # Returns 15
If you want to either replace one string with another string or to change the order of characters in a string,
use re.sub() .
re.sub() allows you to use a regular expression to specify the pattern of the string you want to swap.
In the code below, we replace 3/7/2021 with Sunday and replace 3/7/2021 with 2021/3/7.
import re
match_pattern = r"(\d+)/(\d+)/(\d+)"
Containers
Containers are any object that holds an arbitrary number of other objects. Generally, containers provide a
way to access the contained objects and to iterate over them.
Python includes several built-in container types: lists, dictionaries, sets, and tuples:
from collections import Container # Can also use "from typing import Sequence"
# Note that the "dict" datatype is also a mapping datatype (along with being a container
isinstance(dict(), collections.Mapping) # Prints True
Lists
A list is the Python equivalent of an array, but is resizable and can contain elements of different types:
l[0] # Access a list like you would any array; returns "1"
l[-1] # Negative indices count from the end of the list; prints "2"
As usual, you can find all the gory details about lists in the Python documentation.
If you want access to the index of each element within the body of a loop, use the built-in enumerate
ISD Moldova - Eastern Europe Outsourcing
function: OPENEN
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
soft.com
animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
List Comprehensions
List comprehensions are a tool for transforming one list (any iterable actually) into another list. During this
transformation, elements can be conditionally included in the new list and each element can be transformed
as needed.
Every list comprehension can be rewritten as a for loop but not every for loop can be rewritten as a list
comprehension.
The key to understanding when to use list comprehensions is to practice identifying problems that smell like
list comprehensions.
If you can rewrite your code to look just like this for loop, you can also rewrite it as a list comprehension:
new_things = []
for item in old_things:
if condition_based_on(item):
You can rewrite the above for loop as a list comprehension like this:
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
if x % 2 == 0
squares.append(x ** 2)
squares # Returns [0, 4, 16]
nums = [0, 1, 2, 3, 4]
[x ** 2 for x in nums if x % 2 == 0] # Returns [0, 4, 16]
nums = [0, 1, 2, 3, 4]
[x ** 2 for x in nums] # Returns [0, 1, 4, 9, 16]
You can also use if / else in a list comprehension. Note that this actually uses a different language
construct, a conditional expression, which itself is not part of the comprehension syntax, while the if after
the for … in is part of the list comprehension syntax.
nums = [0, 1, 2, 3, 4]
On the other hand, list comprehensions can be equivalently written using a combination of the list
constructor, and/or map and/or filter :
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
list(map(max, [1, 2, 3], [4, 2, 1])) # Returns [4, 2, 3]
soft.com
list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # Returns [6, 7]
Nested Loops
flattened = []
for row in matrix:
for n in row:
flattened.append(n)
Nested loops in list comprehensions do not read like English prose. A common pitfalls is to read this list
comprehension as:
But that’s not right! We’ve mistakenly flipped the for loops here. The correct version is the one above.
When working with nested loops in list comprehensions remember that the for clauses remain in the
same order as in our original for loops.
Slicing
In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this
is known as slicing:
nums[2:] # Get a slice from index 2 to the end; returns "[2, 3, 4]"
nums[:2] # Get a slice from the start to index 2 (exclusive); returns "[0,
nums[:] # Get a slice of the whole list; returns "[0, 1, 2, 3, 4]"
Assigning to a slice (even with a source of different length) is possible since lists are mutable:
nums1 = [1, 2, 3]
nums1[1:] = [4, 5] # Assign a new sublist to a slice
nums2 = nums1
nums2[1:] = [6] # Assign a new sublist to a slice
id(nums1) == id(nums2) # Returns True since lists are mutable, i.e., can be changed in-p
List Functions
l = [1, 2, 3]
# Note that "l_copy is l" will result in False after this operation.
del l_copy[2] # Remove arbitrary elements from a list with "del"; l_copy is now [1, 2
# Note that l.insert(n, 3) would return the same output, where n >= len
# for example, l.insert(3, 3).
l.index(3) # Get the index of the first item found matching the argument; returns
# l.index(4) # Raises a ValueError as 4 is not in the list
OPENEN
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
soft.com
l + l_copy # Concatenate two lists; returns [1, 2, 3, 1, 2, 3]
# Again, this is similar to using the "extend()" method; with the only
# difference being that "list.extend()" carries out the operation in pl
# while '+' creates a new list object (and doesn't modify "l" and "l_co
l.append(l_copy) # You can append lists using the "append()" method; returns [1, 2, 3,
List concatenation using .extend() can be achieved using the in-place addition operator, += .
l = [1, 2, 3]
l += [4, 5, 6] # Returns "[1, 2, 3, 4, 5, 6]"
# Note that l += 4, 5, 6 works as well since the source argument on the right is already
Instead of needing to create an explicit list using the source argument (on the right), as a hack, you can
simply use a trailing comma to create a tuple out of the source argument (and thus imitate the above
functionality):
l = [1, 2, 3]
l += 4 # TypeError: 'int' object is not iterable
l[1:] = 10, # Equivalent to l[1:] = (10,); same effect as l[1:] = [10]; returns "[1
Dictionaries
A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript. In other
words, dictionaries store mappings from keys to values.
You can use it like this:
You can find all you need to know about dictionaries in the Python documentation.
In the above snippet, four does not exist in d . We get a KeyError when we try to access d[four] .
As a result, in many situations, we need to check if the key exists in a dictionary before we try to access it.
<dict>.get()
The get() method supports a default argument which is returned when the key being queried is missing:
A good use-case for get() is getting values in a nested dictionary with missing keys where it can be
ISD Moldova - Eastern Europe Outsourcing
challenging to use a conditional statement: OPENEN
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
soft.com
fruits = [
{"name": "apple", "attr": {"color": "red", "taste": "sweet"}},
{"name": "orange", "attr": {"taste": "sour"}},
{"name": "grape", "attr": {"color": "purple"}},
{"name": "banana"},
]
colors = [fruit["attr"]["color"]
if "attr" in fruit and "color" in fruit["attr"] else "unknown"
for fruit in fruits]
colors # Returns ['red', 'unknown', 'purple', 'unknown']
In contrast, a better way is to use the get() method twice like below. The first get method will return an
empty dictionary if the key attr doesn’t exist. The second get() method will return unknown if the key
color doesn’t exist.
defaultdict
We can also use collections.defaultdict which returns a default value without having to specify one
during every dictionary lookup. defaultdict operates in the same way as a dictionary in nearly all aspects
except for handling missing keys. When accessing keys that don’t exist, defaultdict automatically sets a
default value for them. The factory function to create the default value can be passed in the constructor of
defaultdict .
default_list_d = defaultdict(list)
default_int_d = defaultdict(int)
We can also pass in a lambda as the factory function to return custom default values. Let’s say for our
default value we return the tuple (0, 0) .
Using a defaultdict can help reduce the clutter in your code, speeding up your implementation.
Python also provides a nice way of iterating over the keys inside a dictionary. However, when you are iterating
over keys in this manner, remember that you cannot add new keys or delete any existing keys, as this will
result in an RuntimeError .
for key in d:
print(d[key]) # This is OK
del
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-# Delete key "numbers" of d
del d["one"]
soft.com
d.get("four", "N/A") # "four" is no longer a key; returns "N/A"
Key Datatypes
Note that as we saw in the section on tuples, keys for dictionaries have to be immutable datatypes, such as
ints, floats, strings, tuples, etc. This is to ensure that the key can be converted to a constant hash value for
quick look-ups.
valid_dict = {(1, 2, 3): [1, 2, 3]} # Values can be of any type, however.
Get all keys as an iterable with keys() . Note that we need to wrap the call in list() to turn it into a list,
as seen in the putting it all together section on iterators. Note that for Python versions <3.7, dictionary key
ordering is not guaranteed, which is why your results might not match the example below exactly. However,
as of Python 3.7, dictionary items maintain the order with which they are inserted into the dictionary.
Get all values as an iterable with values() . Once again we need to wrap it in list() to convert the
iterable into a list by generating the entire list at once. Note that the discussion above regarding key ordering
holds below as well.
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"
If you want access to keys and their corresponding values, use the items method:
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"
Dictionary Comprehensions
These are similar to list comprehensions, but allow you to easily construct dictionaries.
As an example, consider a for loop that makes a new dictionary by swapping the keys and values of the
original one:
flipped = {}
for key, value in original.items():
flipped[value] = key
As another example:
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
Sets
ISD Moldova - Eastern Europe Outsourcing
OPENEN
A setteams
Outsourcing services provided by dedicated is an of
unordered
Java andcollection of distinct
.NET developers. isd-elements. In other words, sets do not allows duplicates and thus
soft.com lend themselves for uses-cases involving retaining unique elements (and removing duplicates) canonically.
As a simple example, consider the following:
animals = set()
animals.add('fish', 'dog') # Returns "{'fish', 'dog'}"
valid_set = {(1,), 1}
s = {1, 2, 3}
s1 = s.copy() # s is {1, 2, 3}
s1 is s # Returns False
Set Operations
other_set = {3, 4, 5, 6}
filled_set & other_set # Returns {3, 4, 5}
As usual, everything you want to know about sets can be found in the Python documentation.
Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot
make assumptions about the order in which you visit the elements of the set:
Set Comprehensions
Like lists and dictionaries, we can easily construct sets using set comprehensions.
As an example, consider a for loop that creates a set of all the first letters in a sequence of words:
first_letters = set()
for w in words:
OPENEN
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
soft.com That same code written as a set comprehension:
first_letters = {w[0] for w in words}
As another example:
Tuples
A tuple is an immutable ordered list of values.
t = (1, 2, 3)
t[0] # Returns "1"
t[0] = 3 # Raises a "TypeError: 'tuple' object does not support item assignment"
Note that syntactically, a tuple of length one has to have a comma after the last element but tuples of other
lengths, even zero, do not:
A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in
dictionaries and as elements of sets, while lists cannot:
l = [1, 2]
d[l] # Raises a "TypeError: unhashable type: 'list'"
len(tup) # Returns 3
You can find all you need to know about tuples in the Python documentation.
Type Hinting
Introduced in Python 3.5, the typing module offers type hint functionality, which documents what type the
contents of the containers needed to be.
In the function greeting below, the argument name is expected to be of type str (annotated as
ISD Moldova - Eastern
name:Europe
str ) and the Outsourcing
return type str . Subtypes are accepted as arguments.
OPENEN
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
soft.com
def greeting(name: str) -> str:
return 'Hello ' + name
Type Aliases
A type alias is defined by assigning the type to the alias. In this example, Vector and list[float] will
be treated as interchangeable synonyms:
Vector = list[float]
Type aliases are useful for simplifying complex type signatures. For example:
...
# The static type checker will treat the previous type signature as
def broadcast_message(
message: str,
servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
...
Note that None as a type hint is a special case and is replaced by type(None) .
Any
The Any type is special in that it indicates an unconstrained datatype. A static type checker will treat every
type as being compatible with Any and Any as being compatible with every type.
This means that it is possible to perform any operation or method call on a value of type Any and assign it to
any variable:
a: Any = None
a = [] # OK
a = 2 # OK
s: str = ''
s = a # OK
item.bar()
...
Notice that no typechecking is performed when assigning a value of type Any to a more precise type. For
example, the static type checker did not report an error when assigning a to s even though s was
declared to be of type str and receives an int value at runtime!
Furthermore, all functions without a return type or parameter types will implicitly default to using Any :
def legacy_parser(text):
...
return data
...
ISD Moldova - Eastern Europe
return data Outsourcing
OPENEN
Outsourcing services provided by dedicated teams of Java and .NET developers. isd-
soft.com