keep-loving-pythonのブログ

Pythonを愛し続けたいです(Pythonが流行っている限りですが。。。)

解決策。AttributeError: 'Namespace' object has no attribute 'func'

解決策。AttributeError: 'Namespace' object has no attribute 'func'

AttributeError: 'Namespace' object has no attribute 'xxx'

xxxの部分は、いろいろ。

エラーの内容

エラー

AttributeError: 'Namespace' object has no attribute 'func'

エラー詳細

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    args.func(args) # Error is here
AttributeError: 'Namespace' object has no attribute 'func'

環境

windows10
python3.7

解決策

エラーの出し方

サンプルコード

import argparse

def PrintSuru(args):
    print("Print: Print shimasu")
    exit(0)

parser = argparse.ArgumentParser()
subparser = parser.add_subparsers()
printooo = subparser.add_parser("printooo", help="korekara tsukuru")

printooo.set_defaults(func=PrintSuru)

args = parser.parse_args()
args.func(args) # Error is here

このコードは、以下を参考にしました。

https://gist.github.com/amarao/36327a6f77b86b90c2bca72ba03c9d3a

上記のコードで、
以下のように、引数をつけるとエラーになりません。

>python test.py printooo
Print: Print shimasu

エラーの解説

Namespaceとは

このNamespaceは、argparseの関係で定義されているクラスです。
いわゆる一般用語としてのNamespaceではない。

'Namespace' object has no attribute 'func' とは

これは、引数をつけると、funcというattributeが付加されるということでしょう。
argparse 自体を理解して下さい。

コメント

これは、役立つかも。。。