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

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

РКН clck.ru/3Ko7Hq
Download Telegram
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
When you do obj.x = y you can't be sure that the attributed of obj named x is now equal to y. Python descriptor protocol lets define how attribute assignment is handled.

class Descriptor:
def __set__(self, obj, value):
obj.test = value

class A:
x = Descriptor()


In this example, x is never assigned, but the test attribute is assigned instead:

In : a = A()
In : a.x = 42
In : a.test
Out: 42
In : a.x
Out: <__main__.Descriptor at 0x7ff7baef51d0>


In case you actually need to change the x attribute as a part of tests or advanced metaprogramming, you have to modify __dict__ directly:

In : a.__dict__['x'] = 42

In : a.x
Out: 42
🔥5
Forwarded from Реальный Python
Обнаружение объектов с помощью цветовой сегментации изображений в Python

https://nuancesprog.ru/p/3968/

👉 @python_real
👍2
To store any information in memory or on a storage device, you should represent it in bytes. Python usually provides the level of abstraction where you can think about data itself, not its byte form.

Still, when you write, say, a string to a file, you deal with a physical structure of data. To put characters into a file you should transform them into bytes; that is called encoding. When you get bytes from a file, you probably want to convert them into meaningful characters; that is call decoding.

There are hundreds of encoding methods out there. The most popular one is probably Unicode, but you can't transform anything to bytes with it. In the sense of byte representation, Unicode is not even an encoding. Unicode defines a mapping between characters and their integer codes. 🐍 is 128 013, for example.

But to put integers into a file, you need a real encoding. Unicode is usually used with utf-8, which is (usually) a default in Python. When you read from a file, Python automatically decodes utf-8. You can choose any other encoding with encoding= parameter of the open function, or you can read plane bytes by appending b to its mode.
👍7
Подборка каналов для IT специалистов 🎯

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

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

Java разработка 📌
https://t.me/BookJava Библиотека Java разработчика
https://t.me/java_360 Книги по Java Rus

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

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

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

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

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

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

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

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

Библиотеки 📌
https://t.me/book_for_dev Книги для программистов 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/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/UchuEnglish Английский с нуля

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

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

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

Метавселенная, GameFi, Crypto 📌
https://t.me/metaverse360

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

Мир технологий 📌
https://t.me/mir_teh Видео из мира технологий

Excel лайфхак📌
https://t.me/Excel_lifehack
👍2
Превращаем текст в числа

Пакет Numerizer преобразует обычный текст в числа. То есть, например, из строки "forty two" можно получить число "42".

https://github.com/jaidevd/numerizer
🔥3👍1
Open source инструмент на Python для выбора признаков нейронной сети

Поиск и выбор наиболее полезных признаков в датасете — одна из наиболее важных частей машинного обучения. Ненужные признаки уменьшают скорость обучения, ухудшают возможности интерпретации результатов и, что самое важное, уменьшают производительность работы.

В этой статье мы рассмотрим работу FeatureSelector. Он позволяет нам быстро внедрять эти методы, обеспечивая более эффективный рабочий процесс. Feature Selector — это незавершенный проект, который будет продолжать улучшаться в зависимости от потребностей сообщества.
🔥3
Шаблоны и практика глубокого обучения
Ферлитш Эндрю (2022)

Откройте для себя шаблоны конструирования и воспроизводимые архитектуры, которые направят ваши проекты глубокого обучения от стадии разработки к реализации. В книге рассматриваются актуальные примеры создания приложений глубокого обучения с учетом десятилетнего опыта работы автора в этой области. Вы сэкономите часы проб и ошибок, воспользовавшись представленными здесь шаблонами и приемами. Проверенные методики, образцы исходного кода и блестящий стиль повествования позволят с увлечением освоить даже непростые навыки. По мере чтения вы получите советы по развертыванию, тестированию и техническому сопровождению ваших проектов. Издание предназначено для инженеров машинного обучения, знакомых с Python и глубоким обучением.

Скачать

👉 @python_360
👍10
If you create new objects inside your __init__ it may be better to pass them as arguments and have a factory method instead. It separates business logic from technical details on how objects are created.

In this example __init__ accepts host and port to construct a database connection:

class Query:
def __init__(self, host, port):
self._connection = Connection(host, port)


The possible refactoring is:

class Query:
def __init__(self, connection):
self._connection = connection

@classmethod
def create(cls, host, port):
return cls(Connection(host, port))


This approach has at least these advantages:

• It makes dependency injection easy. You can do Query(FakeConnection()) in your tests.
• The class can have as many factory methods as needed; the connection may be constructed not only by host and port but also by cloning another connection, reading a config file or object, using the default, etc.
• Such factory methods can be turned into asynchronous functions; this is completely impossible for __init__.
👍7👎1