How to import mw, solution, and friends while inside a module

Let's say I have a module like this:

```
# module1

def print_message(msg):
mw.message(msg)
```

Say also I have a second module which is a script. Inside of this script, I want to import module1 and use it in that module:

```
# my module

import module2

module2.print_message("hello mecway world!")
```

However an error occurs ("global name 'mw' is not defined") when importing module1, because the module1 globals() doesn't contain mw. Is there a way I can import the mw, solution, etc modules inside of my module1? I have already tried this:

import mw

But that doesn't work.

NOTE: I want to do things this way because there is a lot of code in module1.py that needs to be separated from module2.py, because it is being reused quite a bit.

Comments

  • edited October 2020
    Unfortunately, imported modules don't have the global variables and they aren't part of any library or module that you can import.

    A workaround is to add your own mw variable in the imported module from the importing module before using it, like this:

    module1.py:
    def print_message(msg):
    mw.message(msg)
    main_script.py:
    import module1
    module1.mw = mw
    module1.print_message("hello world")
  • Good workaround! Thanks.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!