Is it possible to make a module iterable in Python?

I am creating a module that I want to consider as a static container of objects. These objects have the class type that I defined. I want to be able to import this module and then loop through the objects inside. Here is some code explaining what I mean:

example.py

class MyExampleClass(object): def __init__(self, var1, var2, var3): self.var1 = var1 self.var2 = var2 self.var3 = var3 self.var4 = var4 instanceA = MyExampleClass(1, 2, 3, 4) instanceB = MyExampleClass(4, 3, 6, 7) instanceC = MyExampleClass(5, 3, 4, 5) # something like this def __iter__(): return (instanceA, instanceB, instanceC) 

Then I would like to be able to import this and use it as an enumeration:

 import example for e in example: # do stuff with e 

Can this be done in Python? Or will I need to import the list from the example package?

example.py

 objects = (instanceA, instanceB, instanceC) 

and then

 import example for e in example.objects: # do stuff with e 
+5
source share
2 answers

You can achieve this by specifying the root class in your module and replacing the module with an instance of this class. Here is an example:

 class ModuleClass(object): __init__(self): self.instanceA = MyExampleClass(1, 2, 3, 4) ... __iter__(self): # Your iterator logic here # and then in the same module code sys.modules[__name__] = ModuleClass() 

So you can do what you want, because when you import this module, it will actually be an instance of your custom iterative ModuleClass :

 import example for e in example: # do stuff with e 
+3
source

Although I do not recommend it, you can create your own module, inheriting from types.ModuleType . Then you can replace the source module with your own class sys.modules[__name__] = NewModule()

 import types import sys class MyExampleClass(object): def __init__(self, var1, var2, var3, var4): self.var1 = var1 self.var2 = var2 self.var3 = var3 self.var4 = var4 class MyModule(types.ModuleType): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.instanceA = MyExampleClass(1, 2, 3, 4) self.instanceB = MyExampleClass(4, 3, 6, 7) self.instanceC = MyExampleClass(5, 3, 4, 5) def __iter__(self): return iter([self.instanceA, self.instanceB, self.instanceC]) sys.modules[__name__] = MyModule("example") # Name of the module 
+3
source

All Articles