Aller au contenu principal
ProduitsOutils de bureauTASTECADConsultation de plansTASTEFILESGestion de fichiersTASTEFTPTransfert de fichiersTASTESSHEspace de travail à distanceTASTEZIPCompression et extractionTASTEWINMGestion de fichiersOutils pour développeursTASTECODEEnvironnement de développement intégré pour RustTASTESTUDIOEnvironnement intégré de développement et de testTASTEETLIntégration de données (ETL)ServeursTASTEREMOTEServeur de bureau à distanceTASTEGEOServeur géospatialTASTEMAILEspace de travail e-mailInvestissementTASTESTOCKApplication de bureau de trading automatique d'actionsCommencerTéléchargementsDocumentationAcheterTous les produits
Marketplace
Actualités
TechActualitésL’actu dev du jourDocs développeursLangages de programmationRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks d'applications et de bureauTauriFlutterReact NativeElectronAlgorithmesBases des algorithmesAlgorithmes essentielsAlgorithmes avancésAlgorithmes pratiques
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrineGuide de la communauté
CollaborerTransfert techniqueRéalisation de site webRéalisation d'application de bureauChaîne de publication et de paiementPartenaire commercialContact
ServicesBureau à distancePaquets d'installation sur mesure
TASTEDEV
Produits

Outils de bureau

TASTECADDes plans complexes, ouverts en toute légèretéTASTEFILESSeulement les fichiers utiles, au plus viteTASTEFTPLe chemin le plus net pour vos fichiersTASTESSHEntre vos serveurs et vous, un lien plus solideTASTEZIPCompresser plus vite, extraire en toute sécuritéTASTEWINMUn gestionnaire de fichiers à deux volets, pensé pour le clavier

Outils pour développeurs

TASTECODEModifier, compiler, déboguer et tester vos apps Rust dans une seule fenêtreTASTESTUDIODe l’édition aux tests à distance et aux corrections IA approuvéesTASTEETLDéplacer les données, les valeurs sous les yeux

Serveurs

TASTEREMOTEUn bureau à distance hébergé sur votre propre serveurTASTEGEOUn serveur géospatial compatible GeoServer, reconstruit en RustTASTEMAILReprenez la maîtrise de vos e-mails

Investissement

TASTESTOCKDu trading automatique d'actions selon vos règles : quand, et quoi

Commencer

TéléchargementsDernières versions de chaque produitDocsUtiliser chaque produitAcheterAbonnements et licences perpétuellesTous les produitsTous les produits en un coup d’œil
Tous les produits
MarketplaceActualités
Tech

Actualités

L’actu dev du jourAnnonces officielles : langages, frameworks, GitHub et IADocs développeursGuides des langages, frameworks et algorithmes

Langages de programmation

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks d'applications et de bureauTauriFlutterReact NativeElectron

Algorithmes

Bases des algorithmesAnalyse de complexité · Tri · Recherche · Structures de données de base · Arbres et tasAlgorithmes essentielsParcours de graphe · Plus courts chemins et arbres couvrants · Programmation dynamique · Algorithmes gloutons · Diviser pour régner · Backtracking (retour sur trace)Algorithmes avancésAlgorithmes sur les chaînes · Mathématiques et théorie des nombres · Manipulation de bits · Arbres de segments · Union-FindAlgorithmes pratiquesStratégie pour les entretiens de codage · Cache LRU · Limitation de débit · Hachage cohérent
Toute la documentation de développement
Communauté
ProjetsDécouvrir les créateurs et leurs travauxJournaux de développementDécisions et enseignementsPromptsInstructions réutilisablesProblèmes d’outils d’IAProblèmes et contournements de Claude, Codex, GeminiVitrineRéalisations terminéesGuide de la communautéConstruire en toute transparence
Collaborer
Transfert techniqueApplications natives en Rust et eguiRéalisation de site web10 langues, comptes, documentation et téléchargementsRéalisation d'application de bureauRust et egui, sans WebViewChaîne de publication et de paiementSignature, MSI, deb, rpm, AppImage, empreintesPartenaire commercialRecommandez-nous, touchez 30 %ContactDéveloppement, partenariats, investissement
Services
Bureau à distanceAccédez à votre ordinateur depuis le navigateurPaquets d'installation sur mesureSeulement l'utile, réglages préchargés
Acheter
FR
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Se connecter
Se connecter
TASTEDEV

Des petits outils à un meilleur développement.

support@tastedev.netSoutenir TASTEDEV
ProduitsGamme de produitsAcheterDocsTéléchargementsMarketplaceAssistance
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrine
RèglesÀ proposPolitique de confidentialitéConditions d'utilisationConditions d’abonnementRemboursementRègles de la communauté
CompteSe connecterS'inscrire
Visiteurs
Aujourd’hui
Hier
Vues au total
Société
GXSOFT
Représentant
CHOI YOUNG GU
Numéro d’enregistrement
853-44-00368
Adresse
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Téléphone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsable de la confidentialité
CHOI YOUNG GU

© 2026 TASTEDEVLes informations produit s'appuient sur des sources de développement vérifiées.Publié · en amélioration

Documentation Python
Python
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts
Discussions

Guide Python · 6/6

Key Concepts

Ce chapitre n'est disponible qu'en anglais pour le moment.

"Pythonic" code leans on the language's own tools to say things briefly and clearly. This chapter covers the machinery behind that style: iterators, generators, comprehensions and decorators, followed by the habits that make code feel natural to experienced Python developers.

Iterators

A for loop works on anything iterable: lists, strings, dicts, files, ranges and more. Under the hood, the loop calls iter() to get an iterator, then calls next() repeatedly until the iterator raises StopIteration.

numbers = [10, 20, 30]
it = iter(numbers)
next(it)   # 10
next(it)   # 20
next(it)   # 30
# one more next(it) raises StopIteration

# zip and enumerate return iterators as well
names = ["mina", "joon"]
scores = [90, 85]
for rank, (name, score) in enumerate(zip(names, scores), start=1):
    print(rank, name, score)

Because iterators produce values on demand, they can walk through huge data sets without loading everything into memory. The flip side is that an iterator is single-use: once exhausted, it stays exhausted.

Generators

Any function containing yield is a generator function. Calling it does not run the body; it returns a generator object that executes up to the next yield each time a value is requested, then pauses. It is by far the easiest way to write a custom iterator.

def countdown(n: int):
    while n > 0:
        yield n
        n -= 1


list(countdown(3))   # [3, 2, 1]


def read_lines(path: str):
    with open(path, encoding="utf-8") as f:
        for line in f:
            if line.strip():
                yield line.rstrip("\n")


def numbered(lines):
    for i, line in enumerate(lines, start=1):
        yield f"{i}: {line}"


# stream a large file through a pipeline, one line at a time
for row in numbered(read_lines("log.txt")):
    print(row)

Use yield from to delegate to another iterable. The standard itertools module adds building blocks such as islice, chain and groupby for composing iterators.

Comprehensions

Comprehensions build a list, dict or set from a loop and an optional condition in a single expression. Swap the brackets for parentheses and you get a generator expression, which produces values lazily instead of building a collection up front.

nums = range(10)

squares = [n * n for n in nums]                 # list
evens = [n for n in nums if n % 2 == 0]         # with a filter
lengths = {w: len(w) for w in ["py", "rust"]}   # dict
initials = {w[0] for w in ["apple", "avocado"]} # set {'a'}

total = sum(n * n for n in nums)                # generator expression
pairs = [(x, y) for x in range(2) for y in range(2)]

Comprehensions shine when they are short. Once you are stacking several loops and conditions and the line no longer reads at a glance, an ordinary loop is the better choice.

Des questions sur ce chapitre ?
Chapitre précédentErrors and Testing
for

Decorators

Functions in Python are values: you can store them in variables and pass them around. A decorator is a function that takes a function and returns a new one with extra behavior, applied with the @name syntax. Decorators are ideal for cross-cutting concerns such as logging, timing, access checks and caching.

import functools
import time


def timed(func):
    @functools.wraps(func)          # keep the original name and docstring
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            print(f"{func.__name__}: {time.perf_counter() - start:.4f}s")
    return wrapper


@timed
def slow_add(a, b):
    time.sleep(0.1)
    return a + b


@functools.lru_cache(maxsize=None)   # memoization from the standard library
def fib(n: int) -> int:
    return n if n < 2 else fib(n - 1) + fib(n - 2)


slow_add(1, 2)
fib(80)

You have already met several decorators: @property, @staticmethod, @classmethod and @dataclass all work this way.

Writing Pythonic code

Type import this in the REPL to print "The Zen of Python", a short statement of the language's design values. In practice, these habits get you most of the way:

  • Loop over values directly rather than over indexes; use enumerate when you need a counter and zip to walk sequences in parallel.
  • Open resources with with and let context managers handle cleanup.
  • Prefer "easier to ask forgiveness than permission" (EAFP): try the operation and handle the exception, rather than checking every precondition first.
  • Lean on built-ins such as sum, any, all, sorted and max(key=...).
  • Choose readable over clever. Readability counts.
users = [{"name": "mina", "active": True}, {"name": "joon", "active": False}]

# not very Pythonic
active = []
for i in range(len(users)):
    if users[i]["active"] == True:
        active.append(users[i]["name"])

# Pythonic
active = [u["name"] for u in users if u["active"]]
has_inactive = any(not u["active"] for u in users)

Summary

  • for loops run on the iterator protocol (iter and next), and iterators produce values lazily.
  • Generators written with yield let you process large data step by step with little memory.
  • Comprehensions build collections concisely; fall back to a loop when they get complicated.
  • Decorators move shared behavior out of function bodies; always use functools.wraps in your wrappers.

To keep going, the official documentation is the best next stop:

  • Python documentation
  • The Python Tutorial
  • The Python Standard Library
  • Python Packaging User Guide
  • PEP 8 style guide

0 commentaire

Meilleurs commentairesPlus récents d'abord

Se connecter · Connectez-vous pour laisser un commentaire.