Skip to content

Python

Python3 on MacOS in a right way

  • Install pyenv
    brew install pyenv 
    pyenv install 3.8.0
    pyenv global 3.8.0
    
  • Add the following to your configuration file (.zshrc for me, possibly .bash_profile for you):
    export PATH="/Users/denis/.pyenv/shims:${PATH}"
    export PYENV_SHELL=zsh
    source '/usr/local/Cellar/pyenv/1.2.15/libexec/../completions/pyenv.zsh'
    command pyenv rehash 2>/dev/null
    pyenv() {
      local command
      command="${1:-}"
      if [ "$#" -gt 0 ]; then
        shift
      fi
    
      case "$command" in
      rehash|shell)
        eval "$(pyenv "sh-$command" "$@")";;
      *)
        command pyenv "$command" "$@";;
      esac
    }
    
    Now we know for certain that we're using Python 3.8.0 and pip will update alongside it without any manual aliasing between versions.

Lambda, map, reduce, filter

# Lambda
foo = lambda n: n**2 if n % 2 == 0 else n**3
foo(5)
# Output: 125

# Map
col = [6, 10, 12, 15, 19]
mapped = map(lambda x: x*10, col)
# mapped = [60, 100, 120, 150, 190]

# Filter
filtered = filter(lambda x: x % 2 == 0 and x > 7, col)
# filtered = [10, 12]

# Reduce
from functools import reduce
reduced = reduce(lambda x, y: x * y + 10, col)
# reduced = 242450

globals() locals()

1
2
3
4
type(<object>) -> <ClassName> 
isinstance(<object>, <ClassName>) -> Boolean
globals() -> dict with global vars
locals() -> dict with local vars

Context managers

with open("example.txt", "w") as file:
    # logic
Two special methods: enter() and after(). They take care of what happens when execution enters and exits your with block respectively..

from datetime import datetime

class DataManager():
    def __init__(self):
        self.file = None

    def __enter__(self):
        now = str(datetime.now()).split(".")[0].replece(" ", "-").replace.(":","-")
        filename = now + "-DATA.txt"
        self.file = open(filename, "w")
        return self.file

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.file.close()
        print ("File closed")

with DataManager() as data:
    data.write("hello!")

Decorators

def is_positive(func):
    def wrapper(*args, **kwargs):
        for arg in args:
            if arg < 0:
                raise Exception("Negative Number!")
        return func(*args, **kwargs)
    return wrapper

@is_positive
def my_function(agr1, agr2):
    return arg1 + arg2

Same decorations with class and special method call():

class is_positive():
    def __init__(self, func):
        self.function = func

    def __call__(self, *args, **kwargs):
        for arg in args:
            if arg < 0:
                raise Exception("Negative Number!")
        return self.function(*args, **kwargs)

@is_positive
def my_function(agr1, agr2):
    return arg1 + arg2

Generators

def squares(a, b):    
    i = a    
    while i < b:        y
        yield i**2
        i += 1

s = squares(5, 10)
next(s)

urllib module for web requests

You can do a lot of neat stuff with it e.g. access API resources, make different types of HTTP requests like GET, POST, PUT, DELETE etc.

Simple request to google.com to see what we get.

import urllib.request

with urllib.request.urlopen("https://www.google.com/") as url:
    print(url.read(300).decode("utf-8"))

GET request

import urllib.request

req = urllib.request.Request(url = 'https://jsonplaceholder.typicode.com/todos/1')

with urllib.request.urlopen(req) as resp:
    print(resp.read().decode('utf-8'))

POST request

import json
import urllib.request

# This is our Todo
data = {
    "userId": 101,
    "id": 100,
    "title": "This is a POST request",
    "completed": True
}

# Dump the todo object as a json string
data = json.dumps(data)

req = urllib.request.Request(url = 'https://jsonplaceholder.typicode.com/todos/', data = bytes(data.encode("utf-8")), method = "POST")

# Add the appropriate header.
req.add_header("Content-type", "application/json; charset=UTF-8")

with urllib.request.urlopen(req) as resp:
    response_data = json.loads(resp.read().decode("utf-8"))
    print(response_data)

PUT request

import json
import urllib.request

# This is our Todo
data = {
    "userId": 1,
    "id": 1,
    "title": "This is a PUT request",
    "completed": False
}

# Dump the todo object as a json string
data = json.dumps(data)

req = urllib.request.Request(url = 'https://jsonplaceholder.typicode.com/todos/1', data = bytes(data.encode("utf-8")), method = "PUT")

# Add the appropriate header.
req.add_header("Content-type", "application/json; charset=UTF-8")

with urllib.request.urlopen(req) as resp:
    response_data = json.loads(resp.read().decode("utf-8"))
    print(response_data)

DELETE request

import json
import urllib.request

req = urllib.request.Request(url = 'https://jsonplaceholder.typicode.com/todos/1', method = "DELETE")

with urllib.request.urlopen(req) as resp:
    response_data = json.loads(resp.read().decode("utf-8"))
    print(response_data)

Comments