Sachin Jain
Sachin Jain

Reputation: 21842

How to access objects from another module?

I have a python script which defines a couple of objects like this

# A.py
a - some dict
b - some dict
c - some dict
d - some dict

Now, I have another script B.py in which I want to access a,b,c,d but it based on some variable, I would select which of those to use

# By.py
import A as A_objects

input = 'a'

# Since the input is 'a' here, I want to call A_objects.a.value
print(A_objects.input.value) # Does not work

Here is the error:

AttributeError: module 'A' has no attribute 'input'

This sounds like a basic problem to me but I am unable to find a solution. One approach which I have in mind is to create a dictionary with string and objects like

global_dict = { 'a': a, 'b': b ... }

And get objects/dicts as global_dict.get(input) in B.py Let me know what is the best practice of achieving this use case.

Upvotes: 1

Views: 1454

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Your problem is not to "access objects from another module", but to resolve an attribute (names defineds in a module become attributes of the module object) by it's name. You'd have the exact same problem for any object, ie:

class Foo():
    def __init__(self):
        self.a = 42

f = Foo()

name = 'a'

# now how to get 'f.<name>' ?

And the generic answer is the builtin getattr(object, name[, default]) function:

print(f.a)
print(getattr(f, name))

So in your case in B.py you'd want

print(getattr(A_objects, input))

BUT if you're dealing with user inputs (for the largest possible definition of "user inputs"), you most probably want to explicitely define which names are ok to be accessed this way - using a dict being the most obvious solution:

# a.py

a = {}
b = {}
# etc

registry = {
   "a": a,
   "b": b,
   # etc
}

and:

# B.py
import A
input = 'a'
print(A.registry[input])

Upvotes: 2

Orelus
Orelus

Reputation: 1023

You can simply do getattr(A_objects, input)

Upvotes: 4

Related Questions