Skip to content

Instantly share code, notes, and snippets.

@FuruNov
Created March 27, 2023 22:50
Show Gist options
  • Select an option

  • Save FuruNov/280c9d3fa944cd9ff7fc059a4569447d to your computer and use it in GitHub Desktop.

Select an option

Save FuruNov/280c9d3fa944cd9ff7fc059a4569447d to your computer and use it in GitHub Desktop.
関数の指定した引数への再代入を禁止する Python プログラム
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