1

In a module, I have two functions, let's call them f and g. g takes a named argument f. I'd like to call f from inside g. How do I access the function f? Unfortunately, due to compatibility issues, I can't change their names.

Edit

To clarify, this is what I mean:

def f():
  ... code ...

def g(f=1):
  ... code ...
  x = f() # error, f doesn't name the function anymore
  ... code ...
1
  • You've got a couple of answers - it'd be good for reference if you could provide some example code to clarify what you mean. Commented Nov 16, 2012 at 17:07

3 Answers 3

7

You could add a new name for the function.

E.g:

def f():
    pass

f_alt = f

def g(f=3):
    f_alt()

Just don't export f_alt from the module.

Sign up to request clarification or add additional context in comments.

4 Comments

It could also be a default argument: def g(f=3, f_alt=f).
That confines the scope and is more elegant, @eryksun. Nice.
Though I'm not pleased with the option of g(4, 6) # fail hard. That is to say — this is not what function parameters are for, and it points out Python's need for a more flexible approach to variable scopes.
Not that it necessarily helps here, but the 'fail hard' scenario is addressed in Python 3 by keyword-only arguments. The signature changes to def g(f=3, *, f_alt=f).
6

Basic example using globals:

def f():
    print 'f'

def g(name):
    globals()[name]()

g('f')

Comments

5

Though globals() seems like a simple solution here, you can also achieve the same thing by defining a inner function inside g() that calls the global f:

def f():print "hello"

def g(f):
    def call_global_f():
        global f
        f()
    call_global_f()      #calls the global f
    print f              #prints the local f

g('foo')

output:

hello
foo

Comments

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.