PYTHON_JOB_INTERVIEW Telegram 1134
🐍 Python-совет: ускоряй импорт и запуск с помощью `__main__` guard и lazy imports

Когда ты пишешь утилиту или CLI‑скрипт, важно не загружать всё сразу. Используй if __name__ == "__main__" + отложенный импорт, чтобы ускорить запуск и избежать лишней инициализации.

🔧 Пример:


# script.py

def main():
import argparse
import time

parser = argparse.ArgumentParser()
parser.add_argument("--sleep", type=int, default=1)
args = parser.parse_args()

print("Start sleeping...")
time.sleep(args.sleep)
print("Done.")

if __name__ == "__main__":
main()


📌 Почему это важно:

• Импорты происходят только при запуске, а не при импорте модуля из другого файла
• Снижается время запуска CLI-инструмента
• Уменьшается нагрузка при unit-тестировании, если main() не нужен
• Позволяет использовать файл как модуль и как скрипт

🛠️ Особенно эффективно при:
• больших CLI-инструментах (`argparse`, rich, pandas и др.)
• работе в средах, где startup time критичен (например, serverless)

🧠 Вывод: if __name__ == "__main__" + локальные импорты = чище, быстрее, гибче.
13👍8🔥2🤔2🥰1



tgoop.com/python_job_interview/1134
Create:
Last Update:

🐍 Python-совет: ускоряй импорт и запуск с помощью `__main__` guard и lazy imports

Когда ты пишешь утилиту или CLI‑скрипт, важно не загружать всё сразу. Используй if __name__ == "__main__" + отложенный импорт, чтобы ускорить запуск и избежать лишней инициализации.

🔧 Пример:


# script.py

def main():
import argparse
import time

parser = argparse.ArgumentParser()
parser.add_argument("--sleep", type=int, default=1)
args = parser.parse_args()

print("Start sleeping...")
time.sleep(args.sleep)
print("Done.")

if __name__ == "__main__":
main()


📌 Почему это важно:

• Импорты происходят только при запуске, а не при импорте модуля из другого файла
• Снижается время запуска CLI-инструмента
• Уменьшается нагрузка при unit-тестировании, если main() не нужен
• Позволяет использовать файл как модуль и как скрипт

🛠️ Особенно эффективно при:
• больших CLI-инструментах (`argparse`, rich, pandas и др.)
• работе в средах, где startup time критичен (например, serverless)

🧠 Вывод: if __name__ == "__main__" + локальные импорты = чище, быстрее, гибче.

BY Python вопросы с собеседований


Share with your friend now:
tgoop.com/python_job_interview/1134

View MORE
Open in Telegram


Telegram News

Date: |

Invite up to 200 users from your contacts to join your channel There have been several contributions to the group with members posting voice notes of screaming, yelling, groaning, and wailing in different rhythms and pitches. Calling out the “degenerate” community or the crypto obsessives that engage in high-risk trading, Co-founder of NFT renting protocol Rentable World emiliano.eth shared this group on his Twitter. He wrote: “hey degen, are you stressed? Just let it out all out. Voice only tg channel for screaming”. During a meeting with the president of the Supreme Electoral Court (TSE) on June 6, Telegram's Vice President Ilya Perekopsky announced the initiatives. According to the executive, Brazil is the first country in the world where Telegram is introducing the features, which could be expanded to other countries facing threats to democracy through the dissemination of false content. Telegram is a leading cloud-based instant messages platform. It became popular in recent years for its privacy, speed, voice and video quality, and other unmatched features over its main competitor Whatsapp. A vandalised bank during the 2019 protest. File photo: May James/HKFP.
from us


Telegram Python вопросы с собеседований
FROM American