Introduction to Advanced Python

Introduction

Dec 2024
@1995parham
python-logo

Parham Alvani

email parham.alvani@gmail.com

home1995parham.github.io

1995parham-logo

Why advanced python?

Zen of Python

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.

Zen of Python (cont'd)

In the face of ambiguity, refuse the temptation to guess.
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.
Now is better than never.
Although never is often better than right now.

Zen of Python (cont'd)

If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea—let's do more of those!

Outline

Python Version

3.6

  • Formatted string literals
  • Underscores in Numeric Literals
  • Syntax for variable annotations
  • Simpler customization of class creation
  • Descriptor Protocol Enhancement
  • asyncio

Trust in docs.python.org

book Python Documentation

Python vs Nodejs

I love them both

favorite

Knowledge is required to understand examples

  • HTTP Protocol
  • Networking Stack
  • Basis of algorithms

Github + Laptop

==

You have the codes

What is Python!?

What is Python!?

Python is a high-level, interpreted and object-oriented scripting language.

Python is designed to be highly readable.

Swap


    a = a + b;
    b = a - b;
    a = a - b;
  

    a, b = b, a
    

Alternative Python Implementations

  • Python (nicknamed CPython)
  • IronPython (Python running on .NET)
  • Jython (Python running on the Java Virtual Machine)
  • PyPy (A fast python implementation with a JIT compiler)
  • Stackless Python (Branch of CPython supporting microthreads)
  • MicroPython (Python running on micro controllers)

Stackless

Stackless Python is an enhanced version of the Python programming language. It allows programmers to reap the benefits of thread-based programming without the performance and complexity problems associated with conventional threads.

  • Microthreads
  • Channels
  • Scheduling
  • Serialization

Python Terminology

PyPi

the Python Package Index

PyPA

The Python Packaging Authority (PyPA) is a working group that maintains many of the relevant projects in Python packaging

pip

The PyPA recommended tool for installing Python packages

Python Package Installation


    $ pip3 install flask
    

  if __name__ == '__main__':
      print('hello world')
  
code hello.py

Storing Data, the right way

  • List - a mutable list of items
  • Dict - unsorted but a fast map of items
  • Set - like a dict without values
  • Tuple - the immutable and hashable list

List

Vector Like Implementation

GetSetLenghtInsertRemove
O(1)O(1)O(1)O(n)O(n)

List (cont’d)


    items = list(range(10))
    primes = [2, 3, 5, 7]

    print([item for item in items])
    print([item for item in items if item not in primes])
    print([item * 2 for item in items if item not in primes])
    
code list.py

Dict

__hash__(key)

GetSetDel
O(1)O(1)O(1)
Do you believe it ?

Set

ExpressionExplanation
spam & eggs
Every item in both
spam | eggs
Every item in either or both
spam - eggs
Every item in the first but not the latter
spam ^ eggs
Every item in either but not both
spam < eggs
True if every item in the first is contained in the latter

Tuple

There are few cases whre a tuple offers some really useful functionalities that a list does not.

Tuple (cont'd)


    t1 = 1, 3, 7, 3
    t2 = (1, 3, 7, 2)

    data = dict()
    data[t1] = 'me'
    data[t2] = 'who'

    import pprint

    pprint.pprint(data)
    
code tuple.py

Data Structure is fun

See Me

<Code Time.py>

Create Person class that can say hello and walk, then create Runner class that inherits from Person.


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

        def say(self):
            print('%s: Hello' % self.name)

        def walk(self):
            print('Telgh Telgh')


    class Runner(Person):
        def __init__(self, name, age):
            super().__init__(name, age)

        def walk(self):
            print('Lekh Lekh')
    
code person.py

Lamba

Lambda expressions (sometimes called lambda forms) are used to create anonymous functions.


    lambda x, y: x * y + 1
    

So what ?!


    import functools

    foo = [1, 2, 3]
    functools.reduce(lambda x, y: x + y, foo)
    
code lambda.py

Scope in python, The LEGB Rule.

extension Local

Names assigned in any way within a function

extension Enclosing-function locals

Name in the local scope of any and all statically enclosing functions

Scope in python, The LEGB Rule. (cont’d)

extension Global

Names assigned at the top-level of a module file, or by executing a global statement in a def within the file

extension Built-in

Names preassigned in the built-in names module

Scope in python, The LEGB Rule. (cont’d)


    def f1():
        a = 1
        b = []

        def f2():
            print(a)
            b.append(1)
        print(b)
        f2()
        print(a)
        print(b)

    f1()
    
code scope.py

Python Packaging


    parent/
        __init__.py
        one/
            __init__.py
        two/
            __init__.py
        three/
            __init__.py
    

Python Packaging (cont'd)

Python defines two types of packages, regular packages and namespace packages.

Regular packages are traditional packages as they existed in Python 3.2 and earlier.

Python Packaging (cont'd)

A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace.

<Code Time.py>

Create calc package for four arithmetic operators (each operator has one file). Then create caculator application based on this package.

code calculator
Fork me on GitHub