0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python 3 エンジニア認定基礎試験 合格に向けて part4 (関数アノテーション)

0
Posted at

定義部分

def f(ham: str, eggs: str = 'eggs') -> str:
  • ham: str → 引数 ham は文字列やで、と注釈してる。
  • eggs: str = 'eggs' → 引数 eggs はデフォルトで 'eggs'、型も文字列やで、と注釈。
  • -> str → この関数の戻り値は文字列を想定してる。

⚠️ ポイント:これは 型チェックを強制するわけじゃなくて、あくまでメタデータ(注釈)。Python 自体は無視するけど、ツール(mypy とか IDE)で活用できる。


実行

print("Annotations:", f.__annotations__)

f.__annotations__ でアノテーションが辞書として取れる。
出力は:

{'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}

つまり:

  • ham は str
  • eggs は str
  • return は str

って情報が残ってる。


呼び出し

f('spam')
  • ham = 'spam'
  • eggs はデフォルトなので 'eggs'
  • 返り値は 'spam and eggs'

✅ まとめると:

  • この例は「関数にアノテーションをつけると、それが __annotations__ という辞書に入る」ことを示してる。
  • 実行結果に型チェックは関与せず、あくまで「補足情報」って感じ。

ここで質問!
ham: str と書いたけど、実際に f(123) って数字を渡したらどうなると思う?

回答と解説

Python 本体はアノテーションを ただの情報(メタデータ) として保存してるだけで、実際の引数チェックはしてくれへん。

だから:

f(123)

って書いたらどうなるかというと…

ham = 123
eggs = 'eggs'

戻り値は

123 and eggs

って評価される。

ただしここで 123 and eggs は論理演算になってしまうから、結果は eggs になる。

エラーにはならんのやけど、意図した動き(文字列連結)にはならんわけやね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?