2020年3月11日 星期三

python tricks

python tricks

Python ticks quick reference

pdb/ipdb

https://docs.python.org/3/library/pdb.html
https://github.com/gotcha/ipdb
pdb

import pdb; pdb.set_trace()

ipdb

import ipdb
ipdb.set_trace()

list comprehension

>> [i for i in range(10) if i != 5]

output

[0, 1, 2, 3, 4, 6, 7, 8, 9]

列出object properties

>> vars(<object>)

f-string

PEP 498

>> a = 1234
>> print(f"a = {a}")
a = 1234

yield - send

asyncio

PEP 492
https://docs.python.org/3/library/asyncio-task.html#coroutines
simple example

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

Running Tasks Concurrently

import asyncio

async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print(f"Task {name}: Compute factorial({i})...")
        await asyncio.sleep(1)
        f *= i
    print(f"Task {name}: factorial({number}) = {f}")

async def main():
    # Schedule three calls *concurrently*:
    await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )

asyncio.run(main())

# Expected output:
#
#     Task A: Compute factorial(2)...
#     Task B: Compute factorial(2)...
#     Task C: Compute factorial(2)...
#     Task A: factorial(2) = 2
#     Task B: Compute factorial(3)...
#     Task C: Compute factorial(3)...
#     Task B: factorial(3) = 6
#     Task C: Compute factorial(4)...
#     Task C: factorial(4) = 24

multiprocessing

multithreading

concurrent

Encoding declarations

https://docs.python.org/3.6/reference/lexical_analysis.html#encoding-declarations
Put the follow comment in the first or second line of the Python script:
-*- coding: <encoding-name> -*-

取得環境變數

import os
os.environ.get('X509_USER_PROXY')

min

這是特別的用法

>>> a = [{"test":{"val1":1}, "name":"A"}, {"test":{"val1":2}, "name": "B"}]
>>> min(a, key=lambda k: k["test"]["val1"])
{'test': {'val1': 1}, 'name': 'A'}

zip

>>> list(zip([1, 2, 3], [4, 5, 6]))
[(1, 4), (2, 5), (3, 6)]

enumerate

>>> list(enumerate(a))
[(0, 'a'), (1, 'b'), (2, 'c')]

getattr

>>>class  A(object):
> ... bar = 1 
> ... 
>>> a = A() 
>>> getattr(a, 'bar')
1

用在自動取得attr時可能會很方便