Reputation: 51
I am trying to define a function which imports modules and place that function in a module of my own so that when I am working on a certain type of project all I need to type is:
import from user *
setup()
#setup is the function which imports the modules
However, whenever I try this, it simply doesn't work. trying to call upon the modules defined in setup after I have run the function only results in an error saying that the modules aren't installed.
Here is the code in my module:
def setup():
import keyboard, win32api, win32con
Let me know if there is any more information I can provide, and thanks for any help.
Upvotes: 0
Views: 59
Reputation: 2764
It's generally a good idea to explicitly import names into your module where you need them, so you can see where things come from. Explicit is better than implicit. But for interactive sessions, it can sometimes be useful to import loads of things at once, so...
You problem is that your setup
method imports these modules into its own namespace, which isn't available outside the function. But you can do something much simpler. If your user
module just contained:
import keyboard, win32api, win32con
Then in your interactive session you could do:
>>> from user import *
These modules should then be available in your session's namespace.
Upvotes: 1
Reputation: 7521
I think you are having a scope problem, if setup is defined in some other module, the import will be valid in that module only (or maybe only in the function that would need to be tested).
As a general matter an "import everything possibly needed" policy is something I would consider wrong. Your code ought only to import what it really needs. Dependencies are better reduced to a minimum and explicit.
Upvotes: 1