0

Supposing, I have a python module called mymodule, it has the following structure:

""" mymodule.py """

mydata = {
    "x": 12,
    "y": 58
}

I want to access to data in the following way:

""" main.py """
import mymodule

print(mymodule.x) # 12
print(mymodule.y) # 58

What should I add to mymodule.py?

I would like to know solutions for Python 2.7 and Python 3.

Fomalhaut
  • 8,590
  • 8
  • 51
  • 95

2 Answers2

1

As per https://stackoverflow.com/a/7668273/783836, it seems to can be done by replacing the module with a class that does what you want:

# module foo.py

import sys

class Foo:
    def funct1(self, <args>): <code>
    def funct2(self, <args>): <code>

sys.modules[__name__] = Foo()

Check the entire post for full details

Community
  • 1
  • 1
user783836
  • 3,099
  • 2
  • 29
  • 34
0

Option 1

If the only data is x and y and you don't want it dynamic you can do something like:

""" mymodule.py """

mydata = {
    "x": 12,
    "y": 58
}

x = mydata['x']
y = mydata['y']

Option 2

Another option is to use addict.Dict but this will require a bit of change in the import.

""" mymodule.py """
from addict import Dict

mydata = Dict({
    "x": 12,
    "y": 58
})

And then to use it:

""" main.py""
from mymodule import mydata

print(mydata.x)
print(mydata.y)

It would be more easier to know why you need it...

Uri Shalit
  • 2,198
  • 2
  • 19
  • 29