0

So I'm writing a program using Python 2.7

from itertools import product
class Foo:
    ordinal_combos = ["".join(map(str, list(x))) for x in product(xrange(8), xrange(8), xrange(8))] # ['000', '001', ...]
    perms_digits = {"0": "---", "1": "--x", "2": "-w-", "3": "-wx", "4": "r--", "5": "r-x", "6": "rw-", "7": "rwx"}
    perms_dict = {x: "".join([perms_digits[y] for y in x]) for x in ordinal_combos}

and I get this error:

Traceback (most recent call last):
 File "/usr/local/lib/python2.7/dist-packages/nose/loader.py", line 418, in loadTestsFromName
  addr.filename, addr.module)
 File "/usr/local/lib/python2.7/dist-packages/nose/importer.py", line 47, in importFromPath
  return self.importFromDir(dir_path, fqname)
 File "/usr/local/lib/python2.7/dist-packages/nose/importer.py", line 94, in importFromDir
  mod = load_module(part_fqname, fh, filename, desc)
 File "/home/automaton/test.py", line 14, in <module>
  class DsefsRecursivePermissionsChangeTest(DsefsTestBase):
 File "/home/automaton/test.py", line 26, in DsefsRecursivePermissionsChangeTest
  perms_dict = {x: "".join([perms_digits[y] for y in x]) for x in ordinal_combos} # {'000': "---------"}, ...
 File "/home/automaton/test.py", line 26, in <dictcomp>
  perms_dict = {x: "".join([perms_digits[y] for y in x]) for x in ordinal_combos} # {'000': "---------"}, ...
NameError: global name 'perms_digits' is not defined

I have looked at the answer to this question: Accessing class variables from a list comprehension in the class definition, which is an answer to why it doesn't work in Python 3 but not in Python 2. Simple list comprehensions and dictionary comprehensions work just fine for me but something in my more complicated code seems to causing this issue.

Anyone have an answer to this?

Amy Fang
  • 11
  • 5
  • 2
    The answer you link to applies to Python 2-3 dict comprehensions and set comprehensions and generator expressions. It is only list-comprehensions that had a fundamentally different implementation that would let you get away with this in Python 2. I am probably going to close as a duplicate unless there are any objections... – juanpa.arrivillaga Jun 11 '18 at 17:37

1 Answers1

0

As per @juanpa.arrivillaga the same issue you linked to applies here. This answer is a community wiki so feel free to add info.

The code works fine without the comprehension and other suggestions are mentioned at that link for additional workarounds like using an __init__ method.

from itertools import product
class Foo:
    ordinal_combos = ["".join(map(str, list(x))) for x in product(xrange(8), xrange(8), xrange(8))] # ['000', '001', ...]
    perms_digits = {"0": "---", "1": "--x", "2": "-w-", "3": "-wx", "4": "r--", "5": "r-x", "6": "rw-", "7": "rwx"}
    perms_dict = {}
    for x in ordinal_combos:
        for y in x:
            perms_dict[x] = "".join(perms_digits[y])

~

Zev
  • 3,423
  • 1
  • 20
  • 41