Created
March 27, 2023 22:50
-
-
Save FuruNov/280c9d3fa944cd9ff7fc059a4569447d to your computer and use it in GitHub Desktop.
関数の指定した引数への再代入を禁止する Python プログラム
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def no_reassign(*arg_names): | |
| def decorator(func): | |
| def wrapper(*args, **kwargs): | |
| original_args = args # 引数をコピーしておく | |
| result = func(*args, **kwargs) # 関数を実行する | |
| # 指定した引数が変更された場合に例外を発生させる | |
| for i, arg_name in enumerate(arg_names): | |
| arg_value = kwargs.get(arg_name, args[i]) | |
| if arg_value != original_args[i]: | |
| raise TypeError("cannot reassign argument '{}'".format(arg_name)) | |
| return result | |
| return wrapper | |
| return decorator | |
| @no_reassign("a") | |
| def test_func(a, b): | |
| b = 0 # OK | |
| # a = 0 # NG: 再代入を禁止するため例外が発生する | |
| return a + b | |
| test_func(1, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment