Search code examples
pythontypesargparse

Expected type '_ActionsContainer', got 'str' instead


import argparse
parser = argparse.ArgumentParser
parser.add_argument('-shortarg', '--longarg', type=type, help="help")
                    ^^^^^^^^^^^

I'm getting an error from argparse about what I believe is the "self" parameter of an argument being a string value (the short argument name). In the problems menu (menu that shows the errors in the program, try inferencing next time), it says Expected type '_ActionsContainer', got 'str' instead. The error I get when running the program says:

Traceback (most recent call last):
  File "NAME OF PROGRAM", line 4, in <module>
    parser.add_argument('-shortarg', "--longarg", type=type, help="help")
  File "argparse.py", line 1401, in add_argument
    chars = self.prefix_chars
AttributeError: 'str' object has no attribute 'prefix_chars'

I'm guessing this is an attribute that '_ActionsContainer' has, but not 'str'.

According to the docs, I don't think this should be happening — the command used in there (command to add argument) gets the same error.


I tried adding an extra string before all of the commands, with the "name" of my argument. I expected this to take over the self parameter and possibly match the format.

What actually happened is that it took over and resulted in the same error. Removing the quotes gave an unsolved reference error instead.

import argparse
parser = argparse.ArgumentParser
parser.add_argument('argname', '-shortarg', '--longarg', type=type, help="help")

Changing the order of the arguments to where the positional parameters are before the keywords has its own error, too.

import argparse
parser = argparse.ArgumentParser
parser.add_argument(type=type, help="help", '-shortarg', '--longarg')

Solution

  • This question was answered by @KarlKnechtel in the comment section.

    The line parser = argparse.ArgumentParser renames the class instead of creating an instance. This can be fixed by adding () to the end of the line.