В Практикуме запустился новый курс — «Тестирование веб-приложений на Python». Этот короткий двухмесячный курс подойдёт ручным тестировщикам с опытом, которые хотят получить новый навык — научиться тестировать веб-приложения на Python. Для старта уметь программировать необязательно.
Эрик Бурыгин, руководитель команды тестирования мобильных приложений в Яндексе и автор курса «Тестирование веб-приложений на Python», рассказал, чем занимается автоматизатор тестирования на Python и как им стать.
→ Первый поток курса «Тестирование веб-приложений на Python» стартует 23 июня.
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__.
Шаблоны и практика глубокого обучения
Ферлитш Эндрю (2022)
Откройте для себя шаблоны конструирования и воспроизводимые архитектуры, которые направят ваши проекты глубокого обучения от стадии разработки к реализации. В книге рассматриваются актуальные примеры создания приложений глубокого обучения с учетом десятилетнего опыта работы автора в этой области. Вы сэкономите часы проб и ошибок, воспользовавшись представленными здесь шаблонами и приемами. Проверенные методики, образцы исходного кода и блестящий стиль повествования позволят с увлечением освоить даже непростые навыки. По мере чтения вы получите советы по развертыванию, тестированию и техническому сопровождению ваших проектов. Издание предназначено для инженеров машинного обучения, знакомых с Python и глубоким обучением.
Скачать
👉 @python_360
В метавселенных можно работать, общаться и даже посещать концерты — все это виртуально 💫 Для чего еще нужны метавселенные и какие возможности они откроют в будущем? Узнайте в финальном выпуске первого сезона подкаста «ZIP. Архив техногенного мира» от команды Газпромбанка.
Слушайте и делитесь > https://vk.cc/cbkbub
Open source инструмент на Python для выбора признаков нейронной сети
Поиск и выбор наиболее полезных признаков в датасете — одна из наиболее важных частей машинного обучения. Ненужные признаки уменьшают скорость обучения, ухудшают возможности интерпретации результатов и, что самое важное, уменьшают производительность работы.
В этой статье мы рассмотрим работу FeatureSelector. Он позволяет нам быстро внедрять эти методы, обеспечивая более эффективный рабочий процесс. Feature Selector — это незавершенный проект, который будет продолжать улучшаться в зависимости от потребностей сообщества.
Что нужно знать о работе автоматизатора тестирования на Python?
Присоединяйтесь 16 июня в 20:00 к открытому уроку OTUS.
Вместе с экспертом поговорим о профессии автоматизатора тестирования на Python, актуальных технологиях, разберем пользу использования автотестов, а также поговорим о нужных навыках и особенностях собеседований. Еще больше об этой профессии вы сможете узнать на онлайн-курсе «Python QA Engineer».
Для регистрации пройдите вступительный тест
Превращаем текст в числа
Пакет Numerizer преобразует обычный текст в числа. То есть, например, из строки "forty two" можно получить число "42".
https://github.com/jaidevd/numerizer
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.
🔥 Чем занимается игровой аналитик и как им стать?
👉🏼 Приглашаем на бесплатный вебинар 14 июня в 20:00 мск онлайн-курса «Игровой аналитик»
👨💻 Вместе с экспертом разберем, кто такой игровой аналитик, каким набором компетенций обладает, рассмотрим пути приводящие в профессию, роль аналитика на проекте, а также задачи, которые он решает.
📌 Регистрация на бесплатный вебинар: https://otus.pw/7oFZ/
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
🔥 Приглашаем 14 июня в 20:00 мск на бесплатный вебинар «Дата инженер и Spark в новых реалиях» онлайн-курса "Spark Developer"
📚На вебинаре мы ответим на вопросы:
✔️ Как изменятся источники и получатели данных, объемы данных, языки для ETL, кластера, облака и IDE?
✔️ Насколько будет востребован дата-инженера на рынке и к чему нужно быть готовым?
👉🏻Регистрация на вебинар: https://otus.pw/YB53/
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():
...
Get Method для словаря
Большинство разработчиков используют скобки, чтобы получить значение из словаря. Но сейчас рекомендуется использовать Get method.
При использовании метода скобок выдается ошибка, если ключ отсутствует. С помощью Get method вы получите “None” .
Подписывайтесь на канал 👉@pythonofff
Распознавание изображений предобученной моделью Inception-v3 c Python API на CPU
Это самый быстрый и простой способ реализовать распознавание изображений на ноутбуке или стационарном ПК без какого-либо графического процессора, потому что это можно сделать лишь с помощью API, и ваш компьютер отлично справится с этой задачей.
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())