Что такое *args и **kwargs в Python?
Функции — это жизнь. Правда? Если вы только начали осваивать Python, неважно — первый ли это ваш язык программирования, или вы пришли в Python из другого языка, то вы уже знаете о том, что количество параметров в объявлении функции соответствует количеству аргументов, которые передают функции при вызове.
Подробнее
Функции — это жизнь. Правда? Если вы только начали осваивать Python, неважно — первый ли это ваш язык программирования, или вы пришли в Python из другого языка, то вы уже знаете о том, что количество параметров в объявлении функции соответствует количеству аргументов, которые передают функции при вызове.
Подробнее
👍11👎2
Forwarded from Python академия
infinity
Самая типичная проблема при написании некоторых сортировок — назначение самой большой переменной. Часто она решается простым вводом большого числа или возведением в степень. Это, конечно, не стареющая классика, но метод максимально не надежный, а главное есть более удачные способы
Не работает с int, требуется использовать именно float.
Подписывайтесь на канал 👉@pythonofff
Самая типичная проблема при написании некоторых сортировок — назначение самой большой переменной. Часто она решается простым вводом большого числа или возведением в степень. Это, конечно, не стареющая классика, но метод максимально не надежный, а главное есть более удачные способы
float('infinity')
или float('inf')
для получения максимально возможного числаfloat('-infinity')
или float('-inf')
для получения минимально возможного числа.Не работает с int, требуется использовать именно float.
Подписывайтесь на канал 👉@pythonofff
👍9🔥1
Unit-tests you write may require some temporary files or directories. The
Since temporary stuff usually should be removed after use,
tempfile
module can help you to achieve that.Since temporary stuff usually should be removed after use,
tempfile
provides context manager as well as plain functions:with tempfile.TemporaryDirectory() as dir_path:
open(os.path.join(dir_path, 'a'), 'w').close()
open(os.path.join(dir_path, 'b'), 'w').close()
open(os.path.join(dir_path, 'c'), 'w').close()
assert files_of(dir_path) == ['a', 'b', 'c']
👍5
👍2
Native Python float values use your computer hardware directly, so any value is represented internally as a binary fraction.
That means that you usually work with approximations, not exact values:
The
That's still can be not enough:
For perfect computations, you can use
The obvious limitation is you still have to use approximations to irrational numbers (such as π).
That means that you usually work with approximations, not exact values:
In : format(0.1, '.17f')
Out: '0.10000000000000001'
The
decimal
module lets you use decimal floating point arithmetic with arbitrary precision:In : Decimal(1) / Decimal(3)
Out: Decimal('0.3333333333333333333333333333')
That's still can be not enough:
In [61]: Decimal(1) / Decimal(3) * Decimal(3) == Decimal(1)
Out[61]: False
For perfect computations, you can use
fractions
, that stores any number as a rational one:In : Fraction(1) / Fraction(3) * Fraction(3) == Fraction(1)
Out: True
The obvious limitation is you still have to use approximations to irrational numbers (such as π).
👍3
Изучаем словари в Python
Словари в Python — это фундаментальный тип данных , представленный в виде пары ключ-значение. Они описываются как объект сопоставления, который сопоставляет хэшируемые значения с произвольными объектами.
Ключи словаря должны быть неизменными, то есть они не могут изменяться. При добавлении в словарь пары ключ-значение он запоминает, в каком порядке они были добавлены. Подробнее.
Словари в Python — это фундаментальный тип данных , представленный в виде пары ключ-значение. Они описываются как объект сопоставления, который сопоставляет хэшируемые значения с произвольными объектами.
Ключи словаря должны быть неизменными, то есть они не могут изменяться. При добавлении в словарь пары ключ-значение он запоминает, в каком порядке они были добавлены. Подробнее.
👍8
Подборка каналов для IT специалистов 🎯
Вакансии 📌
https://t.me/progjob Вакансии для программистов
Системное администрирование 📌
https://t.me/i_DevOps Все для DevOps
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 Чат системных администраторов
Программирование Python 📌
https://t.me/pythonofff Python академия. Учи Python быстро и легко🐍
https://t.me/BookPython Библиотека 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 GameDev: разработка игр
Программирование, Биг дата, книги 📌
https://t.me/bookflow Лекции, видеоуроки, доклады с IT конференций
https://t.me/programmist_of Книги по программированию
https://t.me/proglb Библиотека программиста
https://t.me/bfbook Книги для программистов
https://t.me/coddy_academy Академия кода
Шутки программистов 📌
https://t.me/itumor ITumor | программисты шутят
Защита, взлом, безопасность 📌
https://t.me/thehaking Канал о кибербезопасности
Книги, статьи для дизайнеров 📌
https://t.me/ux_web Статьи, книги для дизайнеров
Английский 📌
https://t.me/UchuEnglish Английский с нуля
Математика 📌
https://t.me/Pomatematike Канал по математике
Арбитраж трафика 📌
https://t.me/partnerochkin CPA и арбитраж трафика
Крипта 📌
https://t.me/bitkoinoff Новости криптовалют
Вакансии 📌
https://t.me/progjob Вакансии для программистов
Системное администрирование 📌
https://t.me/i_DevOps Все для DevOps
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 Чат системных администраторов
Программирование Python 📌
https://t.me/pythonofff Python академия. Учи Python быстро и легко🐍
https://t.me/BookPython Библиотека 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 GameDev: разработка игр
Программирование, Биг дата, книги 📌
https://t.me/bookflow Лекции, видеоуроки, доклады с IT конференций
https://t.me/programmist_of Книги по программированию
https://t.me/proglb Библиотека программиста
https://t.me/bfbook Книги для программистов
https://t.me/coddy_academy Академия кода
Шутки программистов 📌
https://t.me/itumor ITumor | программисты шутят
Защита, взлом, безопасность 📌
https://t.me/thehaking Канал о кибербезопасности
Книги, статьи для дизайнеров 📌
https://t.me/ux_web Статьи, книги для дизайнеров
Английский 📌
https://t.me/UchuEnglish Английский с нуля
Математика 📌
https://t.me/Pomatematike Канал по математике
Арбитраж трафика 📌
https://t.me/partnerochkin CPA и арбитраж трафика
Крипта 📌
https://t.me/bitkoinoff Новости криптовалют
👍2
If you want to pass some information down the call chain, you usually use the most straightforward way possible: you pass it as functions arguments.
However, in some cases, it may be highly inconvenient to modify all functions in the chain to propagate some new piece of data. Instead, you may want to set up some kind of context to be used by all functions down the chain. How can this context be technically done?
The simplest solution is a global variable. In Python, use also may use modules and classes as context holders since they, strictly speaking, are global variables too. You probably do it on a daily basis for things like loggers.
If your application is multi-threaded, a bare global variable won't work for you since they are not thread-safe. You may have more than one call chain running at the same time, and each of them needs its own context. The
Still, both of that approaches are concurrency-unsafe meaning they won't work for coroutine call-chain where functions are not only called but can be awaited too. Once a coroutine does
You can fix that by having the loop set and restore the context every time it resumes some coroutine. The
However, in some cases, it may be highly inconvenient to modify all functions in the chain to propagate some new piece of data. Instead, you may want to set up some kind of context to be used by all functions down the chain. How can this context be technically done?
The simplest solution is a global variable. In Python, use also may use modules and classes as context holders since they, strictly speaking, are global variables too. You probably do it on a daily basis for things like loggers.
If your application is multi-threaded, a bare global variable won't work for you since they are not thread-safe. You may have more than one call chain running at the same time, and each of them needs its own context. The
threading
module gets you covered, it provides the threading.local()
object that is thread-safe. Store there any data by simply accessing attributes: threading.local().symbol = '@'
.Still, both of that approaches are concurrency-unsafe meaning they won't work for coroutine call-chain where functions are not only called but can be awaited too. Once a coroutine does
await
, an event loop may run a completely different coroutine from a completely different chain. That won't work:import asyncio
import sys
global_symbol = '.'
async def indication(timeout):
while True:
print(global_symbol, end='')
sys.stdout.flush()
await asyncio.sleep(timeout)
async def sleep(t, indication_t, symbol='.'):
loop = asyncio.get_event_loop()
global global_symbol
global_symbol = symbol
loop.create_task(indication(indication_t))
await asyncio.sleep(t)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
sleep(1, 0.1, '0'),
sleep(1, 0.1, 'a'),
sleep(1, 0.1, 'b'),
sleep(1, 0.1, 'c'),
))
You can fix that by having the loop set and restore the context every time it resumes some coroutine. The
aiotask_context
module does exactly this by changing the way how tasks are created with loop.set_task_factory
. This works:import asyncio
import sys
import aiotask_context as context
async def indication(timeout):
while True:
print(context.get('symbol'), end='')
sys.stdout.flush()
await asyncio.sleep(timeout)
async def sleep(t, indication_t, symbol='.'):
loop = asyncio.get_event_loop()
context.set(key='symbol', value=symbol)
loop.create_task(indication(indication_t))
await asyncio.sleep(t)
loop = asyncio.get_event_loop()
loop.set_task_factory(context.task_factory)
loop.run_until_complete(asyncio.gather(
sleep(1, 0.1, '0'),
sleep(1, 0.1, 'a'),
sleep(1, 0.1, 'b'),
sleep(1, 0.1, 'c'),
))
👍6
Forwarded from Python академия
Важные методы в Python, которые должен знать каждый python разработчик.
Подписывайтесь на канал 👉@pythonofff
abs()
- возвращает модуль переданного параметра.all()
- функция возвращает значение True, если все элементы в итерируемом объекте - истинны. В противном случае, она возвращает значение False.any()
- функция возвращает True, если какой-либо (любой) элемент в итерируемом объекте является истинным True. В противном случае, any() возвращает значение False.ascii()
- возвращает строку, содержащую печатное представление объекта, и экранирует символы, отличные от ASCII, в строке с помощью экранирования \ x, \ u или \ U.bin()
- функция преобразует целое число в двоичную строку с префиксом 0b. Подписывайтесь на канал 👉@pythonofff
👍5
Media is too big
VIEW IN TELEGRAM
Intro to FastAPI - The Best Way to Create APIs in Python?
Get the code: https://prettyprinted.com/l/xW8
Get the code: https://prettyprinted.com/l/xW8
👍5
Forwarded from Мир технологий и науки (Technology World)
This media is not supported in your browser
VIEW IN TELEGRAM
Подпишись на Мир технологий 👉 @mir_teh
👍3👎3
Сравнение списков в Python
В этой статье мы рассмотрим различные способы, позволяющие осуществить сравнение списков в Python. Для сравнения можно использовать следующие функции:
reduce() и map();
collection.counter();
sort() вместе с оператором ==;
set() вместе с оператором ==;
List Comprehension.
В этой статье мы рассмотрим различные способы, позволяющие осуществить сравнение списков в Python. Для сравнения можно использовать следующие функции:
reduce() и map();
collection.counter();
sort() вместе с оператором ==;
set() вместе с оператором ==;
List Comprehension.
👍4👎1
Both
When you implement
PEP 525 allows you do the same with
for
and with
can be asynchronous. async with
uses __aenter__
and __aexit__
magic methods, async for
uses __aiter__
and __anext__
. All of them are async
and you can await
within them:import asyncio
class Sleep:
def __init__(self, t):
self._t = t
async def __aenter__(self):
await asyncio.sleep(self._t / 2)
async def __aexit__(self, *args):
await asyncio.sleep(self._t / 2)
async def main():
async with Sleep(2):
print('*')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
When you implement
__iter__
you often don't write an iterator with __next__
method, you just use yield
that makes __iter__
a generator:class Bracketed:
def __init__(self, data):
self._data = data
def __iter__(self):
for x in self._data:
yield '({})'.format(x)
print(list(Bracketed([1, 2, 3])))
# ['(1)', '(2)', '(3)']
PEP 525 allows you do the same with
__aiter__
. Both yield
and await
in the function body make it asynchronous generator. While await
is used to communicate with the loop, yield
deals with for
:import asyncio
class Slow:
def __init__(self, data, t=1):
self._data = data
self._t = t
async def __aiter__(self):
for x in self._data:
await asyncio.sleep(self._t)
yield x
async def main():
async for x in Slow([1, 2, 3]):
print(x)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
👍6
Forwarded from BigData
Graph Transformer Architecture
Github: https://github.com/graphdeeplearning/graphtransformer
Paper: https://arxiv.org/abs/2012.09699
👉 @bigdata_1
Github: https://github.com/graphdeeplearning/graphtransformer
Paper: https://arxiv.org/abs/2012.09699
👉 @bigdata_1
👍3
Forwarded from BigData
This media is not supported in your browser
VIEW IN TELEGRAM
🕹 Mastering Atari with Discrete World Models
Github: https://github.com/danijar/dreamerv2
Google research: https://ai.googleblog.com/2021/02/mastering-atari-with-discrete-world.html
Paper: https://arxiv.org/abs/2010.02193
👉 @bigdata_1
Github: https://github.com/danijar/dreamerv2
Google research: https://ai.googleblog.com/2021/02/mastering-atari-with-discrete-world.html
Paper: https://arxiv.org/abs/2010.02193
👉 @bigdata_1
👍2
Consider the following class hierarchy:
Which order will be used to look up the
In order to fix that problem, Python uses C3 superclass linearization, the algorithm that always searches for a method in all child classes before looking up the parent one:
class GrandParent:
pass
class Parent1(GrandParent):
pass
class Parent2(GrandParent):
pass
class Child(Parent1, Parent2):
pass
Which order will be used to look up the
Child.x()
method? The naive approach is to recursively search through all parent classes which gives us Child, Parent1, GrandParent, Parent2
. While many programming languages follow this method indeed, it doesn't quite make sense, because Parent2
is more specific than GrandParent
and should be looked up first.In order to fix that problem, Python uses C3 superclass linearization, the algorithm that always searches for a method in all child classes before looking up the parent one:
In : Child.__mro__
Out:
(__main__.Child,
__main__.Parent1,
__main__.Parent2,
__main__.GrandParent,
object)
👍7
Awesome Python Books
Большинство платных книг, почти все ссылки ведут на amazon.
Содержание:
• Учебные книги
• Структуры и алгоритмы данных
• Разработка игр
• Hardware
• Машинное обучение
• Глубокое обучение
• Обработка естественного языка
• Сети
• Data Analysis
• Безопасность
• SQL и ORM
• Системное администрирование
• Тестирование
• Веб-разработка
• Web Scraping
https://github.com/Junnplus/awesome-python-books
Большинство платных книг, почти все ссылки ведут на amazon.
Содержание:
• Учебные книги
• Структуры и алгоритмы данных
• Разработка игр
• Hardware
• Машинное обучение
• Глубокое обучение
• Обработка естественного языка
• Сети
• Data Analysis
• Безопасность
• SQL и ORM
• Системное администрирование
• Тестирование
• Веб-разработка
• Web Scraping
https://github.com/Junnplus/awesome-python-books
GitHub
GitHub - junnplus/awesome-python-books: :books: Directory of Python books
:books: Directory of Python books. Contribute to junnplus/awesome-python-books development by creating an account on GitHub.
👍6❤1