Python Language Features Summary
Python Language Features Summary
DATA TYPES
-
STRINGS
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
LISTS
o
o
o
o
o
o
o
o
o
Unpacking a list:
x = ([[1,2,3,4,5,6,7],[8,9,10,11,12,13,14]])
a,b = x
a is the first row, b is the second row
Similar to strings for slicing, length, etc
L.append(xyz)
L.pop(2)
# Deleted element at position 2, default value -1
L.extend([3,4,5])
List(reversed(L))
L.remove(spam)
# remove by value
L.count()
Del L[0]
# Delete one item
COMPREHENSIONS
o
[x**2 for x in M if x %2 == 0]
M is an iterable
DICTIONARIES
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
# Dictionary comprehension
o
o
For x in spam:
While (x>0)
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
LOOPS
TUPLES
FILES
o
o
o
o
o
o
o
o
o
o
o
open('f.bin', 'rb')
o
o
SETS
o
o
o
o
o
o
o
o
o
o
OPERATORS
-
STATEMENTS
-
There is a loop else construct where the else is hit if there was no break:
ITERATION PROTOCOL
Any object with a __next__ method supports iteration protocol. It automatically advances
for each call. An iterable object is created by __iter__ call. __next__ raises StopIteration at
the end of the series of results.
Old way to read a file consumes too much memory:
whileTrue:
...line=f .readline()
...if notline:break
... print(line.upper(),end='')
In-built functions:
object with a
next
iternext
call
next
ite r
respectively.
Iter
call creates an
not necessary to create an iterator for it. For lists, it is necessary to create an iterable
because they support multiple open iterations. Objects that are iterable return the
results one at a time and not all at once in a physical list.
ITERABLE OBJECTS:
1.
2.
3.
4.
1.
f = open('script2.py')
lines = f.readlines()
Lines is a list = ['import sys\n', 'print(sys.path)\n', 'x = 2\n', 'print(x ** 32)\n']
2. Can use a conditional if
lines = [line.rstrip() for line in open('script2.py') if line[0] == 'p']
3. Can use nested for
[x + y for x in 'abc' for y in 'lmn']
list
3. Tools such as
sorted
and
tuple
join
method uses an
iteration protocol.
4. Set and Dictionary comprehensions support the extended syntax of list
comprehensions.
5.
Range(x)
6.
map,zip,filter
7.
range
DOCUMENTATION
1. Dir returns list of all attributes in an object.
2. __doc__ - Comments coded at the top of modules, function, class statements etc
are automatically stuffed into the
docstrings
FUNCTIONS
1.
2.
3.
4.
5.
SCOPE
1.
2.
3.
4.
ARGUMENTS
-
In a function call, arguments must appear in this order: any positional arguments
(value); followed by a combination of any keyword arguments (name=value) and the
*iterable form; followed by the **dict form.
In a function header, arguments must appear in this order: any normal arguments
(name); followed by any default arguments (name=value); followed by the *name (or* in
3.X) form; followed by any name or name=value keyword-only arguments (in 3.X);
followed by the **name form.
In both the call and header, the **args form must appear last if present
The steps that Python internally carries out to match arguments before assignment can
roughly be described as follows:
1. Assign nonkeyword arguments by position.
2. Assign keyword arguments by matching names.
3. Assign extra nonkeyword arguments to *name tuple.
4. Assign extra keyword arguments to **name dictionary.
5. Assign default values to unassigned arguments in header.
We can also use a * character by itself in the arguments list to indicate that a function
does not accept a variable-length argument list but still expects all arguments following
the * to be passed as keywords.
Ex:
def kwonly(a, *b, c):
print(a, b, c)
And its usage:
>>> kwonly(1, c=3, b=2)
123
>>> kwonly(c=3, b=2, a=1)
123
>>> kwonly(1, 2, 3)
TypeError: kwonly() takes 1 positional argument but 3 were given
>>> kwonly(1)
TypeError: kwonly() missing 2 required keyword-only arguments: 'b' and 'c'
return a + b + c
LAMBDA FUNCTION-EXPRESSION
1. Lambda is an expression, not a statement
2. Lambdas body is a single expression, not a block of statements. Note that the
following is legal.
def fi():
return 2
fk = lambda x: x + fi()
print(fk(3))
GENERATOR FUNCTIONS
-
Coded as normal def functions but use yield instead retains state between calls.
Generator expression list list comprehensions but generates result on demand.
Generator functions
A function def statement that contains a yield statement is turned into a
generator function. When called, it returns a new generator object with automatic
retention of local scope and code position; an automatically created __iter__
method that simply returns itself; and an automatically created __next__ method
(next in 2.X) that starts the function or resumes it where it last left off, and raises
StopIteration when finished producing results.
Generator expressions
A comprehension expression enclosed in parentheses is known as a generator
expression. When run, it returns a new generator object with the same
automatically created method interface and state retention as a generator
function calls results with an __iter__ method that simply returns itself; and a
_next__ method (next in 2.X) that starts the implied loop or resumes it where it
last left off, and raises StopIteration when finished producing results.
Generators (expressions and functions) are single iteration objects.
TIMING
MODULES
1.
2.
3.
4.
7. There locations to search is form module search path which is set by 4 parameters
Refer to documentation for more details.
OOPS
-
# this prints 2!
But b.x = 3;
a.x = 1
print(b.x)
# this prints 3. This is because b now has its own copy of x.
7. Assignments to attributes in self make per-instance attributes. This means that
these attributes behave like the second example in point 6 above.
8. Classes are attributes in models.
9. Classes can intercept python operators = Operator overloading.
13. Abstract Superclass. In the example below action is not defined with the class
names Super. It is left to the class names sub to define it. It the function is
invoked without defining it, error results. But object creation does work. In the
following code, only b.delegate() fails.
class super:
def delegate(self):
self.action()
class sub1(super):
def action(self):
print("here")
a = sub1()
b = sub2()
a.delegate()
b.delegate()
14. Note that point 13 can also be done with decorators. But when done with
decorators, even instantiation fails unless all methods are defined.
Note that when simply invokes with property key words, the attribute
becomes the fget property for the attribute. In the above example, it
becomes a property of the name attribute.
c. Descriptor Alternate way to intercept attribute access. Properties and
slots are really just a kind of descriptor.
Descriptors are coded as independent classes and provide specially names
accessor methods for tha attribute access operations that they wish to
intercept.
Get, set and deletion methods in the descriptor class are automatically tun
when the attribute assigned to the descriptor class instance is accessed.
Note that all get, set and deletion methods need not be specified. Presence
of any one makes it a descriptor.
A better example:
OPERATOR OVERLOADING
1.
2.
3.
4.
5.
6.
7.
NAME MANGLING
If attributes are prefixed by two underscores, python automatically prefixes it with the
class name. This is useful when we want the variable names to be class_specific. __X
becomes __C__X
FUNCTION DECORATORS
A decorator is a callable that returns a callable. A decorator can be any type of callable
that returns a callable. Note that classes, functions, generators can return items.
Decorators also support nesting.
Ex :
def propmethod(func):
print("here")
return func
class super:
@propmethod
def delegate(self,a):
print("here,%d",a)
a = super()
a.delegate(3)
CLASS DECORATORS
This is similar to function decorators but manages instances created from the class.
The same functionality can be implemented using functions. Note that when defined,
decorators create an object. When the object is subsequently called, the new properties
are applied.