-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Do not allow to pass FileType class object instead of instance in add_argument #81331
Comments
There is a possibility that someone (like me) accidentally will omit parentheses with FileType arguments after FileType, and parser will contain wrong file until someone will try to use it. Example: |
I don't see an easy way around this. FileType is a class, and thus is a callable. add_argument checks that the 'type' parameter is a callable (or a string in the registry). Otherwise it gives the programmer a lot of freedom regarding this parameter. |
Reading the examples in the doc, it's clear the behavior when FileType takes an argument. What's the behavior of FileType when is called without any argument? |
The docs specify what argparse.FileType() does via the default parameters: https://docs.python.org/3/library/argparse.html#argparse.FileType If you mean what does it do when you fail to call it at all (passing type=argparse.FileType), the answer is the same as any other class: It tries to construct a FileType using the user provided argument as the sole positional argument. So if the user passes a valid mode string, it works, and returns a FileType object with that mode string, otherwise it barfs and dumps an error message for passing an invalid argument for FileType. |
Yes, I meant that. Thanks! :) |
If you will run `python test.py hello.txt, where test.py is: import argparse
parser = argparse.ArgumentParser()
parser.add_argument('echo', type=argparse.FileType)
args = parser.parse_args()
print(args.echo) You will receive: I think that can be confusing for someone who will forget to invoke FileType constructor. ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
|
Ah, right. It doesn't actually validate the mode string (it just stores it for when open is called, assuming open will validate it). So yeah, it silently accepts any string, not just valid mode strings. Not a contractual guarantee or anything, just how FileType.__init__ is implemented. |
What if I will add mode check in FileType.__init__? |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: