2

Before I learned the difference between old-style classes and new-style classes I was unaware that object was used for anything by the interpreter. Now I know that to create new-style classes you have to do something like:

class Spam(object):
    pass

In my old code I commonly iterated through lists of objects with stuff like:

for object in xml_objects:
    pass

I can't tell if I'm doing something dangerous and I should go back and find any cases where I did this and create new names. As far as I understand, I'm commandeering object from within the scope of the for loop, but it should be preserved on the outside.

Should I go back and rewrite these loops? If so, is it because it's a matter of bad form or because it can cause real bugs down the road (or both)?

Ben Mordecai
  • 685
  • 2
  • 8
  • 19

1 Answers1

3

It most likely won't cause any problems immediately, as long as you're only writing such for loops within function scope. At the top-level, you potentially could have problems. For example,

for object in [1, 2, 3]:
    pass

class foo(object):
    pass

gives this output:

Traceback (most recent call last):
  File "foo.py", line 4, in <module>
    class foo(object):
TypeError: Error when calling the metaclass bases
    int() takes at most 2 arguments (3 given)

So, I'd fix it when I get a chance. In general, it's good form to avoid shadowing existing names, so that you avoid potential confusion as well as potential runtime errors. In rare cases, you may decide it's worth it, but in the case of object, an abbreviated name like o or obj is customary.

jjlin
  • 4,462
  • 1
  • 30
  • 23