Panda Coder
Panda Coder

Reputation: 157

Make modules available globally

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:

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

Upvotes: 2

Views: 780

Answers (2)

Max
Max

Reputation: 13334

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?

Upvotes: 2

Sylvan LE DEUNFF
Sylvan LE DEUNFF

Reputation: 712

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/

Upvotes: 2

Related Questions