2

Background: I've been trying wrap an entire python file in a class of another file by converting the global variables to static class variables, the methods to class methods... etc. The python file has a class itself, and had global instantiations of that class which means, that the class is now an inner class, and I will need static class variables of that inner class type. [if you have a better way to include entire python files as classes in other python files WITHOUT using modules (I need all code in strictly one file), do tell me. All the same I'm curious to know what's wrong in the below]

I've been able to reduce my issue to the following:

class ok:
    class he: 
        def __init__(self):
            self.x=1
    she=[he() for i in range(3)]

will result in: 'name 'he' is not defined' This works however:

class ok:
    class he: 
        def __init__(self):
            self.x=1
    she=[]
    for i in range(3):
        she.append(he())

To my knowledge both codes result in the same outcome, so why would one be legal and one not?

Confused Soul
  • 358
  • 2
  • 12

1 Answers1

1

I found an even simpler case reproducing your issue : enter image description here The issue is that in the 1st case with list comprehension it looks for a variable toto local to the list comprehension which does not exist (whereas the class attribute toto does exist).
In the second case however there is no list comprehension so it looks for any variable called toto and it finds the class attribute toto.
So the issue comes from the list comprehension and has nothing to do with inner class.

Ismael EL ATIFI
  • 1,939
  • 20
  • 16