ここで説明する少し複雑な問題:
中間値を介して、ある入力を別の入力にマップする関数AB()が必要です。より具体的には、この関数は2つの関数で構成されています。A()とB()を呼び出します。どちらも辞書を返します(つまり、A [B [input]]-> result)
これは私の現在のファイルディレクトリの例です:
packageX/
__init__.py
get_part_of_B_expensively.py
something_that_will_use_convert.py
convert.py
packageA/
__init__.py
get_the_entirety_of_A_expensively.py
私のconvert.pyには次のものがあります:
import get_part_of_B_expensively
from packageA import get_the_entirety_of_A_expensively
dict_A = packageA.get_the_entirety_of_A_expensively()
def get_B():
result = {}
result = get_part_of_B_expensively() # this is a very expensive operation
result += get_rest_of_B_inexpensively() # shorthand for adding two dictionaries
return result # returns a dictionary
dict_B = get_B() # hence why i call it once outside, and not inside AB()
def AB(input):
return dictA[dictB[input]]
get_B()を定義する前にdict_Bを初期化できないため、これが適切であるとは思わないでくださいinput
。また、実装を抽象化したいので、AB()の唯一のパラメーターをにしたいと思います。ただし、主にdict_BとdictAなど、いくつかの変数をグローバルに紹介します。それが最善の方法かどうかはわかりません。get_B()を独自のパッケージに分離することはできますが、それでもグローバルフレームのどこかでそれらを呼び出すことになります。これに対するアプローチがどうあるべきかわからないので、A()とB()を呼び出します。これは、同じパッケージ内のファイルを呼び出す)をできるだけ少なくしますが、関数AB()を抽象化します。