0

As an inexperienced Python user, I would like to ask more experienced users the best approach.

I want to create a series of modules that have the same interface

  • GetDataDescription(file)
  • GetData(file)

Each module takes in a text file and processes it in some simple way. It will return the description on the data extracted and the data itself. (e.g. "count of Letter e", 73, or "Number characters", 760 etc).

I am structuring it like this to make it extendable by adding modules with simple operation but the same interface.

So from my main code I want to import a module and perform the necessary operation on this module (i.e. GetDataDescription and GetData). I could then create a list of module names that have been imported, and say - go process data in these modules

My approach is :-

import countLetters

moduleList = ['countLetters']

m = __import__ (moduleList[0])
func = getattr(m,'countLetters')(logFile)
description = func.GetDataDescription()
print("Data Description: ", description)

However, this is causing a NameError: name 'description' is not defined.

Should I take a different, more Pythonesque approach, or continue to debug.

If debug, then what is wrong with my code above?

Thanks!

LiamD
  • 1
  • 2
  • any particular reason you want the module functions? When you have imported countLetters you could directly call the countLetters function, like `description = GetDataDescription()` You only need to return the description from the function in countLetters – Gerrit Verhaar Dec 02 '16 at 09:53
  • My main reason to go with modules is that for any future extensions I only want to add to the module list, The remainder of the code will stay the same (i.e. print description and print associated data). Again, not sure if this is the best way to do it in python. – LiamD Dec 02 '16 at 09:57
  • I don't see the advantage, because if it is a new module then you need to import it, if it is a new function then you need to call it before it is used. Keeping your general functions in a separate file/module sounds good. You could `import countLetters as cl` to make it more visible that these functions belong to countLetters – Gerrit Verhaar Dec 02 '16 at 10:05
  • or have a look at this thread: http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python?rq=1 – Gerrit Verhaar Dec 02 '16 at 10:17

0 Answers0