LoginSignup
2
1

More than 1 year has passed since last update.

Pythonで引数のデフォルト値として関数呼び出しをするときの注意

Last updated at Posted at 2022-01-05

先に結論

関数を定義した段階で、デフォルト引数で呼び出している関数の結果は確定する。

from time import time
from uuid import uuid4

def some_func(now=time(), uuid=uuid4()):
    print(now, uuid)


some_func()
some_func()
some_func()
some_func()

# >>> 1641341885.5043182 e5ffb9ca-e068-4810-bfa9-3c801734e2b0
# >>> 1641341885.5043182 e5ffb9ca-e068-4810-bfa9-3c801734e2b0
# >>> 1641341885.5043182 e5ffb9ca-e068-4810-bfa9-3c801734e2b0
# >>> 1641341885.5043182 e5ffb9ca-e068-4810-bfa9-3c801734e2b0

実際に自分が起こした問題。

ユーザーインスタンス作成時にuser_idの指定がない場合は新しくUUIDを発行したかった。

from uuid import uuid4

class User:
    def __init__(self, user_id=str(uuid4())) -> None:
        self.id = user_id 

for _ in range(5):
    user = User()
    print(user.id)

# >>> cdbb6136-2a78-46eb-912b-5518cd701345
# >>> cdbb6136-2a78-46eb-912b-5518cd701345
# >>> cdbb6136-2a78-46eb-912b-5518cd701345
# >>> cdbb6136-2a78-46eb-912b-5518cd701345
# >>> cdbb6136-2a78-46eb-912b-5518cd701345

参考

2
1
4

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
2
1