YONG BAGJNS
YONG BAGJNS

Reputation: 531

Call function in other files by using globals()

I am trying to using globals to call the function whose name matches the string. For example:

def abc():
    print('test')

globals()['abc']()  # -> test

but if abc is in another file, how should I call this function.

import file_that_have_abc as imp
globals()['imp.abc']()

will not work because it will call function name 'imp.abc' in recent file instead.

Upvotes: 0

Views: 296

Answers (2)

jsbueno
jsbueno

Reputation: 110766

You just need to use the globals() call to access the variables in your current module. For other modules, just use the name you imported the module with - and to retrieve functions/classes/variables from there from their names as strings, use the getattr function.

For example:

import math
func = `sin`

getattr(math, func)(0)

Upvotes: 0

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160687

Use getattr for accessing members of the module:

func = getattr(globals()['file_that_have_abc'], 'abc')
func()

of course, you can drop the globals here if you don't need to look up the module too.

Upvotes: 2

Related Questions