Posts By: fedorishev

ConfigParser

Очень удобная библиотека для чтения конфигурационной информации из Windows-like .ini файлов.

simple.ini

[bug_tracker]
url = http://localhost:8080/bugs/
username = dhellmann
password = SECRET

configtest.py

from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('simple.ini')

print parser.get('bug_tracker', 'url')

via http://pymotw.com/2/ConfigParser/

virtualenv

Пожалуй, эту вещь надо поставить сразу. Virtualenv позволяет устанавливать сторонние пакеты точечно, для тех проектов, в которых они используются.

pip install virtualenv

# создаем папку project со своими site-packages 
virtualenv --no-site-packages project

cd project

# активируем virtualenv
source bin/activate

# смотрим какие пакеты установлены
yolk -l

# устанавливаем новые 
pip install package

# выходим из виртуальной среды
deactivate

Via http://simononsoftware.com/virtualenv-tutorial/

Быстрая установка web2py

web2py — замечательный питоновский веб-фрэймворк с кучей интересных батареек.

Оказывается, есть отличная утилита, которая устанавливает всю связку apache+python+mod_wsgi+web2py+postgresql (пример для Ubuntu)

wget http://web2py.googlecode.com/hg/scripts/setup-web2py-ubuntu.sh
chmod +x setup-web2py-ubuntu.sh
sudo ./setup-web2py-ubuntu.sh

Отсюда : http://web2py.com/book/default/chapter/13

UPDATE: а можно даже и с nginx/uwsgi  https://web2py.googlecode.com/hg/scripts/setup-web2py-nginx-uwsgi-ubuntu.sh

Строим n-grams

Как получить список n-грамм в четыре строки*

n = 3
with open('/path/to/file') as my_file:
    words = my_file.read().split()
ngrams = zip(*[words[i:] for i in range(n)])

* хорошо бы еще нормализовать регистры, морфологию и пунктуацию до этого

via http://www.quora.com/Python-programming-language-1/What-are-some-cool-Python-tricks#

import this

The Zen of Python, by Tim Peters

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.
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.
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!

Декораторы

Декораторы в Python — это обертки для функций. (Или функции, получающие в качестве параметров другую функции)
Например

@dec2
@dec1
def func(arg1, arg2, ...):
    pass

— то же самое, что и:

def func(arg1, arg2, ...):
    pass
func = dec2(dec1(func))

via PEP 318

git

Краткий мануал (по мотивам  http://git-scm.com/book/ru)

Ставим git

$ apt-get install git

Конфигурируем

$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com

Инициализируем, добавляем файлы, создаем коммит, создаем новый репозиторий и загружаем в репозиторий

 

touch README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/username/projectname.git
git push -u origin master

Выгружаем с репозитория
git fetch origin master

Создаем локальную папку с содержимым репозитория
git clone git://github.com/username/projectname.git

yield

Коротко: yield — это return, возвращающий генератор.

1. Итератор. mylist = [1, 2, 3]. mylist = [x*x for x in range(1,3)]

2. Генератор — это итератор, который можно пройти только один раз. Значения генерируются «на лету» и не хранятся в памяти.

mylist = (x*x for x in range(1,3))

3. yield — функция, возвращающая вместо значения генератор

>>> def createGenerator():
...    mylist = range(3)
...    for i in mylist:
...        yield i*i

вернет генератор, который можно пройти только один раз.

Для чего это нужно? Часто нужно пройти последовательность, не загружая ее в память целиком. Допустим, построчная обработка набора больших файлов:

def get_lines(files):
    for f in files:
        for line in file.readlines():
             yield line

и вызываем:

for line in get_lines(files):
    #обрабатываем строку

via

http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained — лучший ответ

и его перевод : http://habrahabr.ru/post/132554/

Еще:

http://www.kigorw.com/articles/python-yield-generator

http://stackoverflow.com/questions/7883962/where-to-use-yield-in-python-best