0

I have several modules that have the same variable of same name in each. I am trying to write a function that can accept the name of the variable then sum its value over all of the modules. I need to do this because this is the case for several variables.

For example, I have modules moduleA, moduleB, and moduleC that each have within them var1, var2, and var3. I want to write a function that can accept the variable name, say var1 as an argument then calculate:

sum = moduleA.var1 + moduleB.var2 + moduleC.var3

and return the value of sum.

I tried several different ways but kept getting an error that the module does not contain that name. I have included my most recent attempt and the error below.

def sumYearly(name):
    sum = january.name + february.name
    return sum

where january and february are the names of modules and name is the variable I'm trying to use to pass in the variable that exists inside each module. This results in the following error message:

    sum = january.name + february.name
AttributeError: 'module' object has no attribute 'name'
5
  • how do you import modules? Commented Jan 2, 2021 at 17:44
  • 3
    Avoid naming variable after reserved words sum Commented Jan 2, 2021 at 18:04
  • 1
    @Joshua For example, here's an issue that came up after shadowing a builtin: TypeError: 'list' object is not callable in python. BTW, sum is not a keyword, just a builtin. Keywords can't be assigned to, like None and if. Commented Jan 2, 2021 at 18:10
  • @İsmailDurmaz - I am using the following format: from january import january . the module has same name as folder so thats why january shows up twice. Commented Jan 2, 2021 at 21:17
  • @JoshuaNixon - thanks for the advice. I am still new to Python so I will keep that in mind for future reference. Commented Jan 2, 2021 at 21:18

1 Answer 1

3

You can use getattr to dynamically retrieve the value of a variable defined in another module.
Assuming january and february to be two imported modules, then your function becomes:

def sumYearly(name):
    return getattr(january, name) + getattr(february, name)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That worked perfectly! Thanks for taking the time to provide such a detailed answer and example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.