0

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.

belwood
3,86911 gold badges42 silver badges48 bronze badges
asked Apr 16, 2019 at 9:08

2 Answers 2

1

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.

answered Apr 16, 2019 at 9:16
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Apr 16, 2019 at 9:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.