0

I have 3 different modules:

a.py

test_value = 19
........
.......
......
...... # more functions and I need to call every each of it or maybe inherit it

b.py

test_value = 20
....
...
.... #same many functions and each function will need to declare in c.py

My current implementation.

c.py

Here I will call it

import a
import b

String = "I check A"

if "A" in String:
    first = a.test_value
    second = a.xxxxx
    third = a.yyyyy
    More continue
else:
    first = b.test_value
    second = b.xxxxx
    third = b.yyyyy
    More continue

My expectation.

import a
import b

String = "I check A"

if "A" in String:
    first = {}.test_value # the "a" could be replace with depending on the rules.
    ......more continue
else:
    first = {}.test_value # the same here.
    more......

My way might be replacing it example:

if "A" in String:
    replacement_value = a
else:
    replacement_value = b
first = "{}".format(replacement_value).test_value # the "a" could be replace with depending on the rules.
......more continue

this way then I can reuse the code and lessen the number of similar codes but I received erorr : "str' object has no attribute"

Does anyone has any better approach so that I can learn?

Community
  • 1
  • 1
Anonymous
  • 477
  • 3
  • 12
  • Have you tried the simple `if"A" in String: my_module = a` then `first = a.test_value`? – Romain Reboulleau Oct 18 '19 at 05:13
  • What I want is to replace that a.test_value for its "a" with any value depending on my rules. Using a normal call the function within the module I already know it works. What I want is not just calling it – Anonymous Oct 18 '19 at 05:17
  • If it doesn't work that way (although I think it should), you could wrap the values in a dictionary, or any other object. – Romain Reboulleau Oct 18 '19 at 05:18
  • oops sorry there was a typo in my first comment; i meant: `my_module.test_value` – Romain Reboulleau Oct 18 '19 at 05:19
  • I tried the method shared below which uses the same suggestion but I received an error "AttributeError: module 'a' has no attribute 'test_value'" – Anonymous Oct 18 '19 at 05:23

1 Answers1

3

You can assign the module to a variable.

import a
import b

if <some condition>:
    module = a
else:
    module = b
# OR USE
module = a if "A" in String else b

# use it as
module.test_value

You can have the module name as a string and import the module using its name.

module_name = 'a' if 'A' in String else 'b'
module = __import__(module_name)

module.test_value

Try this example. Create 4 files, a.py, b.py, c.py, d.py

a.py

x = 10

b.py

x = 20

c.py

import a
import b

x = input('Enter a value: ')
module = a if x == 'a' else b

print(module.x)

d.py

module = __import__('b')
print(module.x)

Here is the output:
enter image description here

Diptangsu Goswami
  • 5,554
  • 3
  • 25
  • 36