2

I'm trying to make my modules available globally

Filesystem structure

main.py
module_static.py
folder/module_dynamic.py # this is example, but imagine 100s of modules

main.py

print('Loading module_static')
import module_static
module_static.test()

# Trying to make module_static available globally
globals()['module_static'] = module_static
__all__ = ['module_static']

print('Loading module_dynamic')
import sys
sys.path.append('./folder/')
import module_dynamic
module_dynamic.test()

module_static.py

def test():
    print('  -> This is module_static')

module_dynamic.py

def test():
    print('  -> This is module_dynamic')
    module_static.test()

Running main.py creates the following execution flow main.py -> module_dynamic.py -> module_static.py

enter image description here

So as you can see:

  • Loading of modules is working properly
  • However, despite trying to make module_static available globally, it isn't working a module_dynamic.py throws an error saying module_static doesn't exist

How can I make module_static.py available in module_dynamic.py (ideally without having to write any additional code in module_dynamic.py)?

Panda Coder
  • 157
  • 1
  • 9

2 Answers2

2

Not saying it's good practice, but you can do

main.py

import builtins
import module_static
builtins.module_static = module_static

This should allow you to use module_static from anywhere.

More info on builtins: How to make a cross-module variable?

Max
  • 12,794
  • 30
  • 90
  • 142
1

It can't work the way you expect. globals() return a dict of globals variables in your script. Maybe this may help you to understand

enter image description here

You can take a look at this course for better understanding

https://www.python-course.eu/python3_global_vs_local_variables.php

Anyway, you will have to import the module to use it.

If it's just a local tool for your personnal use, you could move it to the folder {Python_installation_folder}/Lib.

Then, in any script, you will be able to do

import module_static

and use your module.

If you want to share your module with other people, publish (upload) it on PyPi. You could follow the tutorial bellow https://anweshadas.in/how-to-upload-a-package-in-pypi-using-twine/

Sylvan LE DEUNFF
  • 682
  • 1
  • 6
  • 21
  • Why can't I use `globals()` to make the module available globally? What I would like to do is control all my modules from `main.py` and not have to worry about module loading from the dynamic modules (I have 100s of them) – Panda Coder Dec 18 '18 at 13:45
  • it doesn't works this way. globals() return a dict of all variables global to your script (at the opposite of local variables which are defined in functions / methods, and doesn't exists in your script's root). See the edited answer – Sylvan LE DEUNFF Dec 18 '18 at 13:49