Is production: true

Python

Python, created by Guido van Rossum and first released in 1991, is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with its notable use of significant indentation.

The language draws developer’s eye sight due to

  • Readability and Simplicity: Python’s clean syntax and emphasis on readability make it easy to learn and use, reducing the cost of program maintenance.
  • Dynamic Typing: Python is dynamically typed, which means you don’t have to declare the type of variables, making it more flexible and faster to develop with.
  • Extensive Standard Library: Python comes with a large standard library that supports many common programming tasks, from connecting to web servers to reading and modifying files.
  • Cross-platform Compatibility: Python is available for all major operating systems like Windows, macOS, and Linux, allowing developers to write code that runs on multiple platforms.
  • Vibrant Community and Ecosystem: Python has a large and active community that contributes to a vast ecosystem of third-party packages and libraries, such as those found in the Python Package Index (PyPI).
  • Support for Multiple Paradigms: Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
  • Extensibility: Python can be extended with modules written in other languages like C or C++, allowing for performance-critical code to be optimized.
  • Automatic Memory Management: Python manages memory automatically via a garbage collector, freeing developers from manual memory management.

Python continues to be one of the most popular programming languages in the world, with a growing community and a constant stream of new libraries and frameworks.

Web Site

Tools

  • Pip
  • Jupyter Notebook
  • PyCharm
  • VS Code

Basic


Use of future For Type Hint in python, before 3.10+, the coding is not easy to understand, especialy when using the syntax "SomeType".

Using from __future__ import annotations

In Python 3.7–3.9, you can enable postponed evaluation of type annotations by importing annotations from the __future__ module. This means all type hints are stored as strings and only evaluated when needed, allowing you to:

  • Use forward references (refer to classes/types before they are defined)
  • Use modern type hint syntax (like | for unions in Python 3.10+)
  • Avoid issues with circular imports in type hints

This feature is enabled by default in Python 3.10, but was reverted in 3.11+ (see PEP 563 and PEP 649 for details). In 3.7–3.9, you must import it explicitly.

Example: Forward Reference in Type Hints

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from __future__ import annotations

class Node:
    def __init__(self, value: int, next: Node | None = None):
        self.value = value
        self.next = next

    def set_next(self, next_node: Node) -> Node:
        self.next = next_node
        return self

head = Node(1)
second = Node(2)
head.set_next(second)

Notes:

  • Tools like mypy and IDEs will interpret type hints as strings when this feature is enabled.
  • For even older Python versions, use string-based type hints: def set_next(self, next_node: 'Node') -> 'Node': ...
  • See PEP 563 and PEP 649 for more details.

group n items in a list to sub list

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

s="""
10.0.0.1
user1
password1
10.0.0.2
user2
password2
"""
s=[ss for ss in s.split('\n') if ss!='']

def pad_every_n_lines(n: int, data: [str])->[[str]]:
    import json
    output = {}
    for index, item in enumerate(s):
        row = index // n
        item_value = index % n
        if str(row) not in output:
            output[str(row)] = {}
        output[str(row)][str(item_value)]=item
    final_output=[]
    for key1 in output:
        arr = []
        for key2 in output[key1]:
            arr.append(output[key1][key2])
        final_output.append(arr)
    return final_output
            
    
[e for e in pad_every_n_lines(3, s)]

# [['10.0.0.1', 'user1', 'password1'], ['10.0.0.2', 'user2', 'password2']]

pad array into dictionary

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12

def pad_arr_as_dict(header: [str],data: [str])->dict[str,str]:
    item ={}
    for index, key in enumerate(header):
        item[key]=data[index]
    return item



pad_arr_as_dict(["ip","un", "pwd"], [ "10.0.0.1", "user1", "password1"])

# {'ip': '10.0.0.1', 'un': 'user1', 'pwd': 'password1'}

Generate string of markdown table

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def gen_md_table(header: [str], data: [dict[str,str]]):
    header_line = " | ".join(header)
    header_line = f"|{header_line}|\n"
    second_line = " | ".join(map(lambda x: "---", header))
    second_line = f"|{second_line}|\n"
    data_rows = "\n".join(map(lambda x: f"|{x}|",map(lambda x: " | ".join(map(lambda y: x[y], header)), data)))
    return header_line+second_line+data_rows

gen_md_table(["ip","un", "pwd"], [
    {"ip":"10.0.0.1","un":"user1","pwd":"password1"},
    {"ip":"10.0.0.2","un":"user2","pwd":"password2"}
])

# |ip | un | pwd|
# |--- | --- | ---|
# |10.0.0.1 | user1 | password1|
# |10.0.0.2 | user2 | password2|

Use python to decode json from stdin

1
2
3
4
5
6
7
8
# pipe in the json data
# then extract as dict in python

# echo '{"a": {"b": 123}}' | \
python3 -c "import sys, json; print(json.load(sys.stdin)['a']['b'])"

# expected resule
# output: 123

A command line tools called jq is also workable, but require extra installation for the tool.


Read/Write data from clipboard

In python read / write data from clipboard, pyperclip is required.

1
2
import pyperclip
data = clipboard_data = pyperclip.paste()

Extract XML data

In python extracting xml data, requires package lxml.

1
2
3
4
from lxml import etree
xml_str="?"
dom = etree.fromstring(xml_str.encode('utf-8'))
len(dom.xpath('//some-tags'))

Read XML from clipboard and load into lxml for processing

1
2
3
4
5
import pyperclip
from lxml import etree
xml_str = clipboard_data = pyperclip.paste()
dom = etree.fromstring(xml_str.encode('utf-8'))
dom.xpath('//{tag}')

Execute OS commands and capture output (subprocess)

Use subprocess to run shell/OS commands from Python and read their standard output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import subprocess

def run_cmd(command: str) -> str:
    process = subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    stdout, stderr = process.communicate()
    stdout = stdout.decode("utf-8", errors="replace").replace("\r\n", "\n")
    stderr = stderr.decode("utf-8", errors="replace").replace("\r\n", "\n")
    return_code= process.returncode
    return return_code, stdout, stderr

return_code, stdout, stderr = run_cmd(f'ls -al')