Фишки Python
29 subscribers
2 photos
3 files
29 links
Всё что ты хотел узнать, но ленился спросить.

Декораторы, итераторы и контракты.
Download Telegram
Необходимо установить расширения line_profiler и memory_profiler
Профилирование

def sum_of_lists(N):
total = 0
for i in range(5):
L = [j ^ (j >> i) for j in range(N)]
total += sum(L)
return total

%prun sum_of_lists(1000000)

14 function calls in 1.089 seconds

Ordered by: internal time

ncalls tottime percall cumtime percall filename:lineno(function)
5 0.817 0.163 0.817 0.163 <ipython-input-1-f105717832a2>:4(<listcomp>)
5 0.220 0.044 0.220 0.044 {built-in method builtins.sum}
1 0.040 0.040 1.077 1.077 <ipython-input-1-f105717832a2>:1(sum_of_lists)
1 0.012 0.012 1.089 1.089 <string>:1(<module>)
1 0.000 0.000 1.089 1.089 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Загрузка расширения для IPython
%load_ext line_profiler
import statsmodels
defaultdict(lambda: 1) - создает структуру словаря с значением по умолчанию
scipy.stats.bernoulli - Bernoulli discrete random variable
Многогранность языка python делает его крайне популярным среди разработчиков.
В данной статье автор делается подборкой полезных хитростей и приемов, которые смогут упростить процесс написания кода

https://nuancesprog.ru/p/1680/

@nuancesprog #статьи #Python #SoftwareDevelopment #Learning
Django templates access to tuples:
{{ t.0.0 }} is like t[0][0] in Python code

{% for option in options %}
<option value="{{ option.0 }}" >{{ option.1 }}</option>
{% endfor %}
Текущий стек вызовов

import traceback
for line in traceback.format_stack():
print(line.strip())
from concurrent.futures import ProcessPoolExecutor
import concurrent.futures

URLS = [ ... ]

def parse(url):
# our logic for parsing the page
return data # still probably a dict

with ProcessPoolExecutor(max_workers=4) as executor:
future_results = {executor.submit(parse, url): url for url in URLS}

results = []
for future in concurrent.futures.as_completed(future_results):
results.append(future.result())
# Это включит автодополнение в консольном режиме python
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")

Как не делать это каждый раз
В файл ~/.pyrc положить:
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")

В ~/.bashrc добавить:

export PYTHONSTARTUP="${HOME}/.pyrc"
export PYTHONIOENCODING="UTF-8"

И, чтобы применить изменение прямо сейчас без перезапуска консоли, выполнить:
source ~/.bashrc
Доступ к словарю по атрибутам:

class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict
__ = self
Словарь с дефолтными значениями для новых ключей, создающимися на лету
d = collections.defaultdict(list)
Именованные кортежи

>>> from collections import namedtuple
>>> A = namedtuple('A', 'count enabled color')
>>> tup = A(count=1, enabled=True, color="red")
>>> tup.count
1
>>> tup.enabled
True
import psutil
import os, sys, time

pid = os.getpid()
p = psutil.Process(pid)
print(' name :', p.name())
print(' exe :', p.exe())

info = p.memory_full_info()
# Convert to MB
memory = info.uss / 1024 / 1024
print('Memory used: {:.2f} MB'.format(memory))