1

I am trying to call a function with a variable though a imported functions file and i am getting a error: AttributeError: 'module' object has no attribute 'i'

I have 3 files I am working with, list.txt functions.py and run.py

In my run.py I am opening list.txt and setting whats there to a list and removing the white space. Then i am looping though the list and trying to call a function based off of the list item. But the code is not taking i as a function but as a str i think. How do i turn i in to something that the function will understand and run?

list.txt contains: foo bar

functions.py

class get_stuff:
    def foo(self):
        print('I just ran foo')
    def bar(self):
        print('I just ran bar')

run.py

import functions
with open(list.txt) as f: 
    xx = [xx.rstrip('\n') for xx in f]
for i in xx: 
    print ('working on item: ' + i )
    functions.get_stuff.i()

I am new to python and am having a hard time finding out a way to fix my problem. I have goolged this for a few hours and while i am finding answers that fit they don't cover imported functions just functions that are in the same script. I might be looking at it the wrong way, maybe I am missing something super easy or this might be the completely wrong way of pythoning! Any help will be great!

Dolyak
  • 13
  • 3
  • Welcome to stackoverflow. i is not callable, is merely a str. Use getattr(i, functions)() to a cal a member by string, it must be callable on functions. – Pedro Rodrigues Dec 19 '18 at 16:17

2 Answers2

1

As I read this, you essentially want to run a function given its name as a string. This can be done using the getattr call. Example:

import functions

myfunc = 'foo'
f = getattr(functions, myfunc)
f()  # Prints 'I just ran foo'

You can simplify it further, if you like:

import functions

myfunc = 'foo'
getattr(functions, myfunc)()  # Prints 'I just ran foo'

Putting this knowledge to work in your example would yield:

import functions

with open(list.txt) as f: 
    xx = [xx.rstrip('\n') for xx in f]

for i in xx: 
    print ('working on item: ' + i )
    getattr(functions, i)()
Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74
0

Your loop for i in xx: defines the i variable, then you call functions.i(). The variable i is not callable as its not a function.

You can use my_function = getattr(<module_name>, <function_name>) to get the function by string. You can then call my_function() as you would any other python function.

RHSmith159
  • 1,823
  • 9
  • 16