LoginSignup
17
18

More than 5 years have passed since last update.

import したモジュールの global 変数にアクセスする方法

Posted at

レガシースクリプト群へ、変更を加える際はテストを義務付けた所、class の無い関数のみのスクリプトに対して、 unittest のコードを書いていたら、 global 変数を利用した関数のテストに出会い、global宣言出来ねーぞ!のエラーが出た。

※ Python2.7

実行

test_aaa.py
import aaa_module

class TestAAA(unittest.TestCase):
    def test_aaa
        aaa_module.aaa_func()

エラー

...
NameError: global name 'logger' is not defined

logger がない。あるあるだよね。

aaa_module.py
if __name__ == '__main__':
    logger = logging.getLogger('...')

global で宣言。あるあるだよね。

global の宣言(妄想)

仕方ないから unittest 側で 以下のようにやってみた。

実行

test_aaa.py
import aaa_module

class TestAAA(unittest.TestCase):
    def test_aaa
        global logger
        logger = logging.getLogger('...')
        aaa_module.aaa_func()

エラー

...
NameError: global name 'logger' is not defined

変わらない。なぜや・・・。

Python に global 変数なんて無かった

参考: Pythonでグローバル変数とか無い、正確にはモジュール内変数。だっけ?

モジュール内変数へのアクセス方法

module.global変数 = 値

実行

test_aaa.py
import aaa_module

class TestAAA(unittest.TestCase):
    def test_aaa
        aaa_module.logger = logging.getLogger('...')
        aaa_module.aaa_func()

まだまだPythonには未知なものが多い

17
18
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
17
18