Skip to Content
入門 Python 3 第3版
book

入門 Python 3 第3版

by Bill Lubanovic, 鈴木 駿, 長尾 高弘
June 2026
Intermediate
804 pages
8h 21m
Japanese
O'Reilly Japan, Inc.
Content preview from 入門 Python 3 第3版

14章型ヒントとドキュメント

見事なヒント以上に怖くてインパクトのあるものは誰も作れない。

—— ハワード・フィリップス・ラヴクラフト

変数がオブジェクトに対する単なる参照となるように、Pythonは設計されている。変数はすべての詳細情報を持つデータに貼り付けられた名札や付箋のような存在である。そのため、例えば変数が参照しているデータ型を明示することはほとんど不要だった。しかし、人間は不完全な存在であり、長いコードブロックの中で名前の綴りを間違えたり、何をしようとしていたのかを忘れたりする。そのため、オプションの型ヒントが追加された。型ヒントはコードの意図を示すために使う。型ヒントはインタプリタが強制する性質のものではなく、ドキュメントとして活用されたり、mypyのようなツールがエラーチェックに利用されたりする。

14.1 型ヒント

静的言語では変数の型を定義しなければならず、コンパイル時にエラーをキャッチできる。しかし、Pythonにはそのような仕組みがないので、コードを実行するまでバグに気付けない場合がある。オブジェクトは厳密な型とメモリ内の位置を持っているが、変数はいつでもどのようなオブジェクトでも指せる名前にすぎない。

しかし、実際のコード(Pythonでもほかの言語でも)では、名前は特定のオブジェクトを参照するのが通常である。少なくともドキュメントとして、コードの要素(変数や関数の返り値など)が参照しているオブジェクトのデータ型をアノテーションで示せれば役立つ。そうすれば、特定の変数がどのように振る舞うかを知るために大量のコードを読まなくても済む。

Python 3.5では、この課題に応えるために型ヒント(型アノテーションとも呼ばれる)が追加された。型ヒントは完全にオプションであり、変数に型を強制しない。しかし、変数の型宣言が必要な(あるいは何らかの方法で推測できる)静的言語に慣れ親しんだプログラマには有用である。型ヒントはあくまでもヒントであり、動作を変えるわけではない。主な用途はドキュメントだが、ほかの用途も広がっている。例えば、WebフレームワークのFastAPI( ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

入門 Python 3 第2版

入門 Python 3 第2版

Bill Lubanovic, 鈴木 駿, 長尾 高弘

Publisher Resources

ISBN: 9784814401642Publisher Website