-1

I'm having a puzzle here trying to figure out what goes on in the machine. This is my code:

import argparse, sys
from scitools.StringFunction import StringFunction

parser = argparse.ArgumentParser()

parser.add_argument('--f', '--function', type=str, default=None,\
                    help='Function', metavar='f')
parser.add_argument('--fn', '--filename', type=str, default=None,\
                    help='Filename', metavar='fn')

args = parser.parse_args()

print args.f and args.fn == None, type(args.fn), type(args.f)

if args.f and args.fn == str:
    f = StringFunction(args.f); filename = args.fn 
else:
    print 'Failed to provide f, filename or both!'
    sys.exit(1)

Running: --f x**2 --fn somename in terminal.

Now the print statement yields:

False <type 'str'> <type 'str'>

in my terminal, but the if test gives:

Failed to provide f, filename or both!

right afterwards! Why does this happen?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Thomas
  • 177
  • 8
  • The `type=...` parameter is not the same as the Python function `type()`. The parameter specifies a function that converts a string into something that you want. You rarely need anything other than `int` or `float`. `str` works but is unnecessary. `bool` is wrong (http://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse/19233287#19233287) – hpaulj Jan 15 '16 at 07:54

1 Answers1

2

The type of args.fn is str, but you test if args.fn is itself equal to it's type. It can't be both.

You are doing this:

>>> type('foo')
<type 'str'>
>>> 'foo' == str
False

Use isinstance() instead:

if args.f and isinstance(args.fn, str):

The better test would be to see if args.fn is not None:

if args.f and args.fn is not None:
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks alot, that solved it and also gave me a better understanding of this type of problem!:) – Thomas Jan 15 '16 at 07:41