1

I'm learning the argparse module, and I wrote code as follows:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
               help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
               const=sum, default=max,
               help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

I saved it as argparse.py, but when I run it in cmd, it shows:

AttributeError: 'module' object has no attribute 'ArgumentParser'

what's the problem? Thank you for your help.

3
  • rename your argparse.py file as you are importing from that, you also need to delete any agparse.pyc file Commented May 31, 2015 at 13:07
  • When you import you are loading yourself, rather than the standard library module. Commented May 31, 2015 at 13:10
  • @evbo: if its any consolation, you are not the first person to have had this issue, and you won't be the last. This issue comes up here at least once a week. Commented May 31, 2015 at 16:43

1 Answer 1

12

When you say import in Python, the interpreter runs a search to find a file with that name. It first looks for the file in the current folder and then in other paths, such as, /usr/lib/python.

Therefore, when you're saying import argparse and naming your script argparse.py, Python takes your file and import it as is.

To avoid this, change the name of your file to something else than argparse.py.

Sign up to request clarification or add additional context in comments.

2 Comments

Happy that I got this in first google search :) Thank you !
So if someone read this in 2023, be patient =). My stupid case is: i had two files in same folder: work/create_parser.py work/argparse.py i tried to call: parser = argparse.ArgumentParser() in file create_parser.py so python3 still throw error: AttributeError: module 'argparse' has no attribute 'ArgumentParser' until i delete\mv file argparse.py =) So that's why imports works in same lvl first

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.