0

I have a module called foo.py from which another module bar.py loads the functions into its namespace. How can I prefix all of the functions in foo.py with the string foo_. An example:

foo.py:

def func1():
  return "hello"

def func2():
  return "world"

bar.py:

from foo import *

def do_something():
  return foo_func1()
user592419
  • 5,103
  • 9
  • 42
  • 67
  • 14
    Why not just `import foo` and then do `foo.func1()`? It's the correct way to use modules and seems very similar to what you're after. – asongtoruin Feb 12 '18 at 15:30
  • 8
    Don't use star imports, then you won't have this name collision problem. See https://stackoverflow.com/questions/2386714/why-is-import-bad – PM 2Ring Feb 12 '18 at 15:30
  • `Namespaces are one honking great idea -- let's do more of those!` -- [The Zen of Python](https://www.python.org/dev/peps/pep-0020/). – Cong Ma Feb 12 '18 at 15:33

1 Answers1

1

Are you looking for something like this?

def do_something( i ):
    import foo
    f = getattr( foo, 'func'+str(i) )
    return f()

print( do_something(1) )  # hello
print( do_something(2) )  # world

you can access an attribute via string by using the oldfashion getattr-function. This will take a object and a string, which you can create during runtime.

docs: getattr(object, name[, default])


EDIT (sorry, completely missread the question)

you can simply use

import foo

and then call the functions with:

foo.funct1()  # hello
foo.funct2()  # world
Skandix
  • 1,916
  • 6
  • 27
  • 36