1

For example, I import json like so import json and now somewhere in the code I want to check if it has been imported. It should be something like: has_imported(module_name).

The reason why I'm asking this is because I'm trying to understand how pkgutil.walk_packages() works. It must import the modules it lists but for some reason some modules are not imported. Seems like I have to import them with a separate function but first this function needs to "know" whether a module that it gets as an argument was imported or not.

There are some similar questions, but I'm far from being satisfied with the answers.

5
  • If you write import json at the top of your file, then you can be pretty sure it's imported in that file. That does not mean it will be imported everywhere (in other files). Might that be a cause of confusion here? Or are you trying to figure out whether any one package has generally been imported by any other module somewhere? (If so, what for?) Commented Aug 31, 2017 at 14:15
  • If you want to know how pkgutil.walk_packages() works, why not just look at its source code? Commented Aug 31, 2017 at 14:17
  • @deceze No, it's not. I import modules with walk_packages (as far as I understand it imports modules on the fly) but some modules in the list don't seem to be imported. I'm just trying to figure out why, Commented Aug 31, 2017 at 14:25
  • 1
    Then you might rather want to ask a concrete question about that…? Commented Aug 31, 2017 at 14:29
  • @deceze I'd already done that before asking this one but no one answered... Commented Aug 31, 2017 at 15:50

1 Answer 1

2

Test for the module name in the sys.modules dictionary:

import sys

print("sys" in sys.modules) #True
print("datetime" in sys.modules) #False
print("json" in sys.modules) #False
Sign up to request clarification or add additional context in comments.

3 Comments

In the interactive mode all of them return True. How is that?
@Foobard, try to open another instance of command line (or what else you are using). I just checked it in my terminal (ver Python 3) - datetime and json checks return False
I've just checked it in my terminal too and yeah now it works as expected. I wonder why it didn't in that terminal. I'm 100% certain I didn't import the modules I checked.

Your Answer

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.