I'm just wondering if it is possible to import a module as an object attribute.
The basic description of what I want to accomplish is that I'm creating a software agent object. This agent will have a set of abilities (functions), but I don't know what these are ahead of time. Logically, it is simplest to encapsulate these abilities in a module, and then have the agent import it. Then it would have access to these abilities. This would also allow it to use the standard modules or any other previously developed modules. Another benefit is that each object has its own namespace for modules. If all modules were in the global namespace of the program, every agent would have access to it. This is something I do not want.
Now I obviously don't know how things work, so I resorted to perhaps one of the worse ways to code something: experimentation. The first thing I tried was to simply attempt to import a module as an object attribute. That failed. Then I checked to ensure that a module could indeed be imported to a local namespace. So I defined a class method that imported the random module, printed the local dictionary, and printed a random number. Then to ensure that the module was only accessible by that function, and not globally, I tried to print a random number in the main function. random was in the local dictionary for the test function, and it printed a random number. The main function raised an exception.
I was going to try to add the module to the local dictionary of the agent, but I learned that local dictionaries cannot be modified. I'm not even sure that an object has a local dictionary anyway. So I was thinking about giving the agent another attribute, a dictionary with holding the agent's modules. That begs two questions. First, how would one call functions using such a dictionary? Second, how do I add modules to the dictionary? I was thinking you could define a method that sets the agent's module attribute as the result of a function that imports a given module, and returns the local dictionary. However, I'm inclined to believe this won't work. I believe objects in a function's local namespace cease to exist when that function exits.
I tested my last assumption, and apparently you can return the locals of an object's method and store them in an attribute. I forgot that locals() returns a copy of the local dictionary. Now I just need to resolve how to call functions from the module name in the dictionary. I'll go ahead and post this while I'm working on it. Maybe someone will come up with an answer before or I do, or maybe I'm going about this the wrong way or there is a better way to do it.
Thank you for reading this. Any help will be appreciated. Thank you.