0

I am having trouble setting a boolean value. My code is:

training_pages_list_file = ''
html_page_dir = ''
clf_file_str = ''
user_idf_param = False

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Classify some CraigsList Pages')
    parser.add_argument('csv_file', action='store')
    parser.add_argument('file_dir', action='store')
    parser.add_argument('clf_file', action='store')
    parser.add_argument('-i', action='store_true', help="include idf", dest=user_idf_param, default=False)
    args = parser.parse_args()

However, this raises:

hon3.4/argparse.py", line 1721, in parse_args
    args, argv = self.parse_known_args(args, namespace)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/argparse.py", line 1742, in parse_known_args
    if not hasattr(namespace, action.dest):
TypeError: hasattr(): attribute name must be string

How can I have it so if -i is included, it will set user_idf_param to True?

2
  • argparse does not set the values of global variables. It sets attributes of the args object that parse_args returns. Commented Mar 8, 2015 at 21:19
  • argparse4j.sourceforge.net/index.html is a Java library modeled on argparse. Commented Mar 8, 2015 at 21:34

1 Answer 1

2

Looks like user_idf_param is supposed to be a name for the attribute that tells you whether or not it was used.

import argparse

training_pages_list_file = ''
html_page_dir = ''
clf_file_str = ''
user_idf_param = "i_param_used"

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Classify some CraigsList Pages')
    parser.add_argument('csv_file', action='store')
    parser.add_argument('file_dir', action='store')
    parser.add_argument('clf_file', action='store')
    parser.add_argument('-i', action='store_true', help="include idf", dest=user_idf_param, default=False)

    args = parser.parse_args((...))

    if args.i_param_used:
        ...
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! That is not at all what I was expecting. The documentation is really bad for this module
The argparse authors probably assumed that users were already familiar with older parsers like optparse and get_opt, and glossed over issues that could confuse Python beginners.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.