1

Consider this code:

class MyMegaClass(object):
    excluded_fields = {1, 2}

    all_fields = list(range(10))
    print(excluded_fields)
    valid_fields = [itm for itm in all_fields if itm not in excluded_fields]
cl = MyMegaClass()
print(cl.valid_fields)

This code works fine on Python 2.7. But Python 3.7 raises an exception on the line with the list comprehension. It doesn't see the "excluded_fields" field. Although, "print(excluded_files)" works! The "excluded_field" is not visible only after "if" in a list comprehension. Any ideas?

The traceback:

Traceback (most recent call last):
File "C:/Users/S2400244/PycharmProjects/enumtest/classfieldtest.py", line 1, in <module>
class MyMegaClass(object):
File "C:/Users/S2400244/PycharmProjects/enumtest/classfieldtest.py", line 6, in MyMegaClass
valid_fields = [itm for itm in all_fields if itm > len(excluded_fields)]
File "C:/Users/S2400244/PycharmProjects/enumtest/classfieldtest.py", line 6, in <listcomp>
valid_fields = [itm for itm in all_fields if itm > len(excluded_fields)]
NameError: name 'excluded_fields' is not defined
dondublon
  • 701
  • 1
  • 6
  • 13

0 Answers0