1

Learning opportunity here. I have a situation where I'm updating certain properties in a file. I have a function that updates the file:

def update_tiapp(property, value):
  print 'update_tiapp: updating "%s" to "%s"' % (property, value)
  for line in fileinput.input(os.path.join(app_dir, 'tiapp.xml')):  # , inplace=True
    if property is 'version':
      line = re.sub(r'(<version>).*?(</version>)', '\g<1>%s\g<2>' % value, line.strip(), flags=re.IGNORECASE)
    elif property is 'brand':
      line = re.sub(r'(<property name="brand" type="string">).*?(</property>)', '\g<1>%s\g<2>' % value, line.strip(), flags=re.IGNORECASE)'\g<1>%s\g<2>' % value, line.strip(), flags=re.IGNORECASE)
    elif property is 'banner-bmp':
      line = re.sub(r'(<banner-bmp>).*?(</banner-bmp>)', '\g<1>%s\g<2>' % value, line.strip(), flags=re.IGNORECASE)
    elif property is 'dialog-bmp':
      line = re.sub(r'(<dialog-bmp>).*?(</dialog-bmp>)', '\g<1>%s\g<2>' % value, line.strip(), flags=re.IGNORECASE)
    elif property is 'url':
      line = re.sub(r'(<url>).*?(</url>)', '\g<1>%s\g<2>' % value, line.strip(), flags=re.IGNORECASE)

All of the conditions are fine except dialog-bmp & banner-bmp. For some reason that I can't understand or find, the condition just won't match. If I change the property and condition to dialog, python is happy to match and make the change for me.

WAT?!

It's an easy change and I don't mind making it, but I'd like to understand.

What is it about the hyphen that blows everything up? Aren't we just string matching here or is there something going on under the hood that I wasn't expecting?

Rob Wilkerson
  • 40,476
  • 42
  • 137
  • 192

1 Answers1

2

Never use is to check for equality (it checks for object identity)! Use == instead:

if property == "version":
    ...
elif property == "brand":
    ...
etc.

is may work for short strings that are interned/cached, but only if they contain nothing but characters that would be valid for a Python identifier (a "variable name"). Your program is a perfect example for this:

>>> a = "dialog-bmp"
>>> b = "dialog-bmp"
>>> a is b
False
>>> id(a)
32571184L
>>> id(b)
32571088L
>>> a = "brand"
>>> b = "brand"
>>> a is b
True
>>> id(a)
32610664L
>>> id(b)
32610664L
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Ah. Just learning Python and it seemed like `is` was what I was seeing in all of the examples. Thanks for the education. – Rob Wilkerson Apr 11 '13 at 12:20