Home > database >  How to import objects from another module as a list
How to import objects from another module as a list

Time:08-31

in moduleA.py:

A = 1
B = 2
C = 3
D = 4

in moduleB.py, how can I achieve:

from moduleA import (A, B, C, D) as nums

for x in nums:
    print(x)

CodePudding user response:

You can't do this the way you are trying to. You will need to find a different solution to your original problem.

CodePudding user response:

Are you looking for something like this?

$ cat moduleB.py
#!/usr/bin/env python

import moduleA

for x in ['A', 'B', 'C', 'D']:
        print(getattr(moduleA, x))

$ ./moduleB.py
1
2
3
4

CodePudding user response:

import a
from a import A,B,C,D

lst = [A, B, C, D]
print('List of nums from a.py is: '   str(lst))

print('Elements in list:')
for x in lst:
    print(x)

Result:

'''
List of nums from a.py is: [1, 2, 3, 4]
Elements in list:
1
2
3
4
'''
  • Related