0

In a text file I have to write values, and next to each value either "NUMERIC" if the value's type is int or float, or "NOMINAL", if the type is str. I know that this could be solved by an if statement, but I would be pleased to use a more elegant way. I thought of multiplication with a boolean - something like that:

outputfile.write(value1 + "_NOMINAL" * (type(value1) is str)
                        + "_NUMERIC" * (type(value1) is (float or int)))

This does not work - I don't know why... It works if I change the second expression into two conditions:

+ "_NUMERIC" * ((type(value1) is float) or (type(value1) is int))

Is there any other elegant, pythonic approach to get this done?

nickie
  • 5,608
  • 2
  • 23
  • 37
aldorado
  • 4,394
  • 10
  • 35
  • 46
  • The first one doesn't work because `(float or int)` resolves to `float`. – Brionius Sep 26 '13 at 15:01
  • `is (float or int)` doesn't do what you think it does. Perhaps you meant `in ( float, int)`. – Robᵩ Sep 26 '13 at 15:01
  • Your code can't possibly work. You should get `TypeError: unsupported operand type(s) for +: 'int' and 'str'` if value1 is ever an int. – Robᵩ Sep 26 '13 at 15:06
  • "Is there any other elegant, pythonic approach to get this done?" for the simple case you've provided I'd say an `if` is the most elegant way. If your actual use is more complicated (this kinda looks like lexical tokenizing) you might get more pleasing results from a `Token` class and subclasses that have appropriate `str` methods. – msw Sep 26 '13 at 15:29

1 Answers1

2

If you really think this is elegant (a matter of taste, I guess), try:

outputfile.write(value1 + "_NOMINAL" * (type(value1) is str)
                        + "_NUMERIC" * (type(value1) in (float, int)))

If you ask me, I think I'd write it like this (assuming the value would only be a string or a number):

print >> outputfile, value1, "NOMINAL" if type(value1) is str else "NUMERIC"

or, if you want to allow for values that are elements of subclasses of str:

print >> outputfile, value1, "NOMINAL" if isinstance(value1, str) else "NUMERIC"

If there were more things changing, depending on the type of the value, or if there were more than two types, I'd use an if.

nickie
  • 5,608
  • 2
  • 23
  • 37
  • would you rather use an `if` statement? I am still a beginner with python and try to learn about good style, too. – aldorado Sep 26 '13 at 15:10