Библиотека Python разработчика | Книги по питону
19.5K subscribers
1.05K photos
391 videos
82 files
988 links
Полезные материалы для питониста по Фреймворкам Django, Flask, FastAPI, Pyramid, Tornado и др.

По всем вопросам @evgenycarter

РКН clck.ru/3Ko7Hq
Download Telegram
Two things in Python can be confused: iterables and iterators.

Iterables are objects that can be iterated, i. e. there is a way to extract some values from that object, one by one, probably infinitely. Iterables are usually some collections like arrays, sets, lists, etc.

There are two ways an object can become a proper iterable. The first one is to have __getitem__ method:

In : class Iterable:
...: def __getitem__(self, i):
...: if i > 10:
...: raise IndexError
...: return i
...:

In : list(Iterable())
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The second way is to define __iter__ method that returns an iterator. An iterator is an object with a __next__ method that returns next value from the original iterable once called:

In : class Iterator:
...: def __init__(self):
...: self._i = 0
...:
...: def __next__(self):
...: i = self._i
...: if i > 10:
...: raise StopIteration
...: self._i += 1
...: return i
...:
...: class Iterable:
...: def __iter__(self):
...: return Iterator()
...:
...:

In : list(Iterable())
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Usually, an iterator also has an __iter__ method that just returns self: it allows iterator to be iterated too, that means that most of the iterators are also iterables.
👍6
Обработка естественного языка в действии
Хобсон Лейн, Ханнес Хапке, Коул Ховард (2020)

Последние достижения в области глубокого обучения позволяют создавать приложения, с исключительной точностью распознающие текст и речь. Что в результате? Появляются чат-боты, ведущие диалог не хуже реальных людей, программы, эффективно подбирающие резюме под заданную вакансию, развивается превосходный предиктивный поиск, автоматически генерируются аннотации документов. Благодаря новым приемам и инструментам, таким как Keras и Tensorflow, сегодня возможно как никогда просто реализовать качественную обработку естественного языка (NLP).
«Обработка естественного языка в действии» станет вашим руководством по созданию программ, способных распознавать и интерпретировать человеческий язык. В издании рассказано, как с помощью готовых пакетов на языке Python извлекать из текста смыслы и адекватно ими распоряжаться. В книге дается расширенная трактовка традиционных методов NLP

Скачать

👉 @python_360
👍4🔥1
In Python, each value has a boolean value. It is implicitly cast when you use if, bool, not etc.

False objects are None, False, 0 of any type, and empty collections: "", [], {} etc., including custom collections with the __len__ method as long as __len__ returns 0.

You can also define custom truth value testing for your objects, the __bool__ magic method is there for this:

class Rectangle:
def __init__(self, width, height):
self._w = width
self._h = height

def __bool__(self):
return bool(self._w and self._h)


In : bool(Rectangle(2, 3))
Out: True
In : bool(Rectangle(2, 0))
Out: False
In : bool(Rectangle(0, 2))
Out: False


Mind, that __bool__ is called __nonzero__ in Python 2.
👍6
One of the most inconsistent part of the Python syntax is tuple literals.

Basically, to create a tuple you just write values separated by commas: 1, 2, 3. OK, so far, so good. What about tuple containing only one element? You just add trailing comma to the only value: 1,. Well, that’s somewhat ugly and error prone, but makes sense.

What about empty tuple? Is it a bare ,? No, it’s (). Do parentheses create tuple as well as commas? No, they don’t, (4) is not a tuple, it’s just 4.

In : a = [
...: (1, 2, 3),
...: (1, 2),
...: (1),
...: (),
...: ]

In : [type(x) for x in a]
Out: [tuple, tuple, int, tuple]


To make things more obscure, tuple literals often require additional parentheses. If you want a tuple to be the only argument of a function, that f(1, 2, 3) doesn’t work for an obvious reason, you need f((1, 2, 3)) instead.
👍2
Подборка каналов для IT специалистов 🎯

Системное администрирование 📌
https://t.me/tipsysdmin Типичный Сисадмин (фото железа, было/стало)
https://t.me/sysadminof Книги для админов, полезные материалы
https://t.me/i_odmin Все для системного администратора
https://t.me/i_odmin_book Библиотека Системного Администратора
https://t.me/i_odmin_chat Чат системных администраторов
https://t.me/i_DevOps DevOps: Пишем о Docker, Kubernetes и др.

Вакансии 📌
https://t.me/sysadmin_rabota Системный Администратор
https://t.me/progjob Вакансии в IT

Чат программистов📌
https://t.me/developers_ru

Excel лайфхак📌
https://t.me/Excel_lifehack

GitHub Сообщество 📌
https://t.me/Githublib Интересное из GitHub

CodePen 📌
https://t.me/codepen_1 Сообщество пользователей CodePen

Базы данных (Data Base) 📌
https://t.me/database_info Все про базы данных

Программирование Python 📌
https://t.me/pythonofff Python академия. Учи Python быстро и легко🐍
https://t.me/BookPython Библиотека Python разработчика
https://t.me/python_real Python подборки на русском и английском

Мобильная разработка: iOS, Android 📌
https://t.me/developer_mobila Мобильная разработка

Фронтенд разработка 📌
https://t.me/frontend_1 Подборки для frontend разработчиков

Java разработка 📌
https://t.me/BookJava Библиотека Java разработчика

Разработка игр 📌
https://t.me/game_devv Все о разработке игр

Библиотеки 📌
https://t.me/book_for_dev Книги для программистов Rus
https://t.me/java_360 Книги по Java Rus
https://t.me/python_360 Книги по Python Rus
https://t.me/programmist_of Книги по программированию
https://t.me/proglb Библиотека программиста
https://t.me/bfbook Книги для программистов

БигДата, машинное обучение 📌
https://t.me/bigdata_1 Data Science, Big Data, Machine Learning, Deep Learning

Программирование 📌
https://t.me/bookflow Лекции, видеоуроки, доклады с IT конференций
https://t.me/coddy_academy Полезные советы по программированию

QA, тестирование 📌
https://t.me/testlab_qa Библиотека тестировщика

Шутки программистов 📌
https://t.me/itumor Шутки программистов

Защита, взлом, безопасность 📌
https://t.me/thehaking Канал о кибербезопасности

Книги, статьи для дизайнеров 📌
https://t.me/ux_web Статьи, книги для дизайнеров
https://t.me/arhitekturamira World Architecture

Английский 📌
https://t.me/UchuEnglish Английский с нуля

Математика 📌
https://t.me/Pomatematike Канал по математике

Арбитраж трафика 📌
https://t.me/partnerochkin CPA и арбитраж трафика

Крипта 📌
https://t.me/bitkoinoff Новости криптовалют

DeepFake 📌
https://t.me/deepfakenow Публикуем deepfake видео

Мир технологий 📌
https://t.me/mir_teh Видео из мира технологий
👍2
If you have a CPU-heavy task and want to utilize all the cores you have, then multiprocessing.Pool is for you. It spawns multiple processes and delegates tasks to them automatically. Simply create a pool with Pool(number_of_processes) and run p.map with the list of inputs.

In : import math
In : from multiprocessing import Pool
In : inputs = [i ** 2 for i in range(100, 130)]
In : def f(x):
...: return len(str(math.factorial(x)))
...:

In : %timeit [f(x) for x in inputs]
1.44 s ± 19.2 ms per loop (...)

In : p = Pool(4)
In : %timeit p.map(f, inputs)
451 ms ± 34 ms per loop (...)

You can also omit the number_of_processes parameter, the default value for it is the number of CPU cores on the current system.
👍3
Градиентый бустинг — просто о сложном

Хотя большинство победителей соревнований на Kaggle используют композицию разных моделей, одна из них заслуживает особого внимания, так как является почти обязательной частью. Речь, конечно, про Градиентный бустинг (GBM) и его вариации. Возьмем, например. победителя Safe Driver Prediction, Michael Jahrer. Его решение — это комбинация шести моделей. Одна LightGBM (вариация GBM) и пять нейронных сетей. Хотя его успех в большей мере принадлежит полуконтролируемому обучению, которое он использовал для упорядочивания данных, градиентный бустинг сыграл свою роль.

Даже несмотря на то, что градиентный бустинг используется повсеместно, многие практики до сих пор относятся к нему, как к сложному алгоритму в черном ящике и просто запускают готовые модели из предустановленных библиотек. Цель этой статьи — дать понимание как же работает градиентный бустинг. Разбор будет посвящен чистому “vanilla” GMB.



@BookPython
🔥7👍5
PEP 8 is a famous style guide for Python code. It's not enforced by the interpreter but you are highly discouraged to ignore it.

There is a tool to automatically check whether your code is following PEP 8 recommendations. Its former name is pep8, but it was renamed to pycodestyle at the request of Guido. Now you should use pycodestyle installed with pip intall pycodestyle only.

You can check whether pycodestyle is happy with your project like this:

$ pycodestyle . -qq --statistics
1 E302 expected 2 blank lines, found 1
1 E305 expected 2 blank lines after class
or function definition, found 1
20 E501 line too long (83 > 79 characters)
👍3🔥1
Forwarded from BigData
👁 Learning Spatio-Temporal Transformer for Visual Tracking

Github: https://github.com/researchmm/Stark

Paper: https://arxiv.org/abs/2103.17154v1

👉 @bigdata_1
👍1
Media is too big
VIEW IN TELEGRAM
Парсинг (скрапинг) сайтов на Python

Быстрый парсинг данных с сайта несколькими процессами с экспортом в csv на Python 3
Парсим Avito .ru при помощи Python 3 (часть 2) - собираем номера телефонов.
Парсинг Avito .ru при помощи Python 3
Парсинг сайтов на Python: Приемы работы с библиотекой BeautifulSoup
Парсинг сайтов на Python: как использовать прокси и менять User-Agent
Парсинг сайтов: анализ "ненормальных" сайтов
Парсинг сайтов: как скачивать картинки и другие файлы
Python: работа с ошибками на примере нерабочих парсеров

https://www.youtube.com/playlist?list=PLlWXhlUMyoobMzou-Hl6HQWcClzg85_TZ
👍7
To be used as a dictionary key, an object should be hashable. Hashable objects support the __hash__ method that returns an integer value. To get a hash of the value, the hash built-in function is used.

Built-in types that are not mutable are hashable by default. All custom objects are also hashable, but there is a catch. If you define __eq__ method for your custom type, then you should define such __hash__ that hash(a) == hash(b) for every a and b that are equal. Violating this rule may result in dictionary malfunctioning:

class A:
def __init__(self, x):
self.x = x

def __hash__(self):
return random.randrange(10000)

def __eq__(self, other):
return self.x == other.x


In : d = {}
In : d[A(2)] = 2
In : d.get(A(2), 0)
Out: 0


Mind that though once you define __eq__ in the class, the default __hash__ method is removed since the default implementation is no longer suitable (with it all values are unequal).
👍5
Подборка каналов для IT специалистов 🎯

Системное администрирование 📌
https://t.me/tipsysdmin Типичный Сисадмин (фото железа, было/стало)
https://t.me/sysadminof Книги для админов, полезные материалы
https://t.me/i_odmin Все для системного администратора
https://t.me/i_odmin_book Библиотека Системного Администратора
https://t.me/i_odmin_chat Чат системных администраторов
https://t.me/i_DevOps DevOps: Пишем о Docker, Kubernetes и др.

Программирование C++📌
https://t.me/cpp_lib Библиотека C/C++ разработчика

Вакансии 📌
https://t.me/sysadmin_rabota Системный Администратор
https://t.me/progjob Вакансии в IT

Чат программистов📌
https://t.me/developers_ru

Excel лайфхак📌
https://t.me/Excel_lifehack

GitHub Сообщество 📌
https://t.me/Githublib Интересное из GitHub

CodePen 📌
https://t.me/codepen_1 Сообщество пользователей CodePen

Базы данных (Data Base) 📌
https://t.me/database_info Все про базы данных

Программирование Python 📌
https://t.me/pythonofff Python академия. Учи Python быстро и легко🐍
https://t.me/BookPython Библиотека Python разработчика
https://t.me/python_real Python подборки на русском и английском

Мобильная разработка: iOS, Android 📌
https://t.me/developer_mobila Мобильная разработка

Фронтенд разработка 📌
https://t.me/frontend_1 Подборки для frontend разработчиков

Java разработка 📌
https://t.me/BookJava Библиотека Java разработчика

Разработка игр 📌
https://t.me/game_devv Все о разработке игр

Библиотеки 📌
https://t.me/book_for_dev Книги для программистов Rus
https://t.me/java_360 Книги по Java Rus
https://t.me/python_360 Книги по Python Rus
https://t.me/programmist_of Книги по программированию
https://t.me/proglb Библиотека программиста
https://t.me/bfbook Книги для программистов

БигДата, машинное обучение 📌
https://t.me/bigdata_1 Data Science, Big Data, Machine Learning, Deep Learning

Программирование 📌
https://t.me/bookflow Лекции, видеоуроки, доклады с IT конференций
https://t.me/coddy_academy Полезные советы по программированию

QA, тестирование 📌
https://t.me/testlab_qa Библиотека тестировщика

Шутки программистов 📌
https://t.me/itumor Шутки программистов

Защита, взлом, безопасность 📌
https://t.me/thehaking Канал о кибербезопасности

Книги, статьи для дизайнеров 📌
https://t.me/ux_web Статьи, книги для дизайнеров
https://t.me/arhitekturamira World Architecture

Английский 📌
https://t.me/UchuEnglish Английский с нуля

Математика 📌
https://t.me/Pomatematike Канал по математике

Арбитраж трафика 📌
https://t.me/partnerochkin CPA и арбитраж трафика

Крипта 📌
https://t.me/bitkoinoff Новости криптовалют

DeepFake 📌
https://t.me/deepfakenow Публикуем deepfake видео

Мир технологий 📌
https://t.me/mir_teh Видео из мира технологий
👍2
Some Python modules are compiled into the interpreter itself. They are called built-in modules, not to be confused with the standard library. One can use sys.builtin_module_names to get the full list of such modules. The notable examples are sys, gc, time and so on.

Usually you don't care whether the module is built-in or not; however, you should be aware, that import always looks for a module among built-ins first. So, the built-in sys module is loaded even if you have sys.py available. On the other hand, if you have, say, datetime.py in the current directory it indeed can be loaded instead of the standard datetime module.
👍5
Forwarded from Python академия
Самый частый элемент

Этот короткий скрипт вернёт элемент, чаще всего встречающийся в списке.

Используются продвинутые параметры встроенной функции max():

• первым аргументом она получает множество из элементов списка (помним, что в множестве все элементы уникальны);
• затем применяет к каждому из них функцию count, подсчитывающую, сколько раз элемент встречается в списке;
• после этого возвращает элемент множества, который имеет больше всего «попаданий».

В качестве аргумента можно использовать списки, кортежи и строки.

Подписывайтесь на канал 👉@pythonofff
👍16
In Python, you can easily modify all standard variables that are available in the global namespace:

>>> print = 42
>>> print(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable


That may be helpful if your module defines some functions that have the same name as built-in ones. That also happens if you practice metaprogramming and you accept an arbitrary string as an identifier.

However, even if you shadow some built-in names, you still may want to have access to things they initially referred to. The builtins module exists exactly for that:


>>> import builtins
>>> print = 42
>>> builtins.print(1)
1


The __builtins__ variable is also available in most modules. There is a catch though. First, this is a cpython implementation detail and usually should not be used at all. Second, __builtins__ might refer to either builtins or builtins.__dict__, depending on how exactly the current module was loaded.
👍3
Dealing with exceptions in asynchronous programs may be not a simple task.

In asyncio, if coroutine raises an exception, it's then propagated to the code that awaits the corresponding future. If multiple places do await, every one of them gets the exception (since it's stored in the exception). The following code prints error five times:

import asyncio

async def error():
await asyncio.sleep(1)
raise ValueError()

async def waiter(task):
try:
await task
except ValueError:
print('error')
else:
print('OK')

async def main():
task = asyncio.get_event_loop().create_task(error())

for _ in range(5):
asyncio.get_event_loop().create_task(waiter(task))

await asyncio.sleep(2)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())


If an exception is raised, but the task is never awaited, the exception is lost. In that case, when the task is destroyed, it warns you with “Task exception was never retrieved” message.

When you use await asyncio.gather(tasks) and one of the tasks raises an exception, it is propagated to you. However, if multiple tasks raise exceptions, you still only get the first one, the others are silently lost:

import asyncio

async def error(i):
await asyncio.sleep(1)
raise ValueError(i)

async def main():
try:
await asyncio.gather(
error(1),
error(2),
error(3),
)
except ValueError as e:
print(e)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())


You may use gather with return_exceptions=True that make it return exceptions as though they are regular result values. The following code prints [42, ValueError(2,), ValueError(3,)]:

import asyncio

async def error(i):
await asyncio.sleep(1)
if i > 1:
raise ValueError(i)
return 42

async def main():
results = await asyncio.gather(
error(1),
error(2),
error(3),
return_exceptions=True,
)

print(results)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
👍3
Распознавание изображений предобученной моделью Inception-v3 c Python API на CPU

Это самый быстрый и простой способ реализовать распознавание изображений на ноутбуке или стационарном ПК без какого-либо графического процессора, потому что это можно сделать лишь с помощью API, и ваш компьютер отлично справится с этой задачей.
👍3
Forwarded from Python академия
Get Method для словаря

Большинство разработчиков используют скобки, чтобы получить значение из словаря. Но сейчас рекомендуется использовать Get method.

При использовании метода скобок выдается ошибка, если ключ отсутствует. С помощью Get method вы получите “None” .

Подписывайтесь на канал 👉@pythonofff
👍7🔥1
Python has a very short list of built-in constants. One of them is Ellipsis which is also can be written as .... This constant has no special meaning for the interpreter but is used in places where such syntax looks appropriate.

numpy support Ellipsis as a __getitem__ argument, e. g. x[...] returns all elements of x.

PEP 484 defines additional meaning: Callable[..., type] is a way to define a type of callables with no argument types specified.

Finally, you can use to indicate that function is not yet implemented. This is a completely valid Python code:

def x():
...
👍4