Is there any way to make possible to use functions in your file before you actually declare their body?
The following code doesn't seem to work:
abc = myFunction
def myFunction():
print "123"
Thanks
Is it possible to execute a python function before declaring it? No! It is not possible. Python does not allow calling of a function before declaring it like C.
If we do not use some function prototypes, and the function body is declared in some section which is present after the calling statement of that function. In such a case, the compiler thinks that the default return type is an integer. But if the function returns some other type of value, it returns an error.
It is always recommended to declare a function before its use so that we don't see any surprises when the program is run (See this for more details).
Is hoisting actually "calling the function before it is defined"? Raising the scope of a declared name so that it will be defined for other code under that scope -- that's roughly what JavaScript does to allow you to call the function before it's declared, and that's hoisting.
You can't use the myFunction
variable before it's assigned. Your example code is similar to:
def myFunction():
print abc
abc = 123
To do what you want, either re-arrange the order:
def myFunction():
print "123"
abc = myFunction
Or declare abc
as just a proxy:
# Style 1
abc = lambda: myFunction()
# Style 2
def abc():
return myFunction()
def myFunction():
print "123"
If your function takes parameters, use *args
and **kwargs
:
# Style 1
abc = lambda *args, **kwargs: myFunction(*args, **kwargs)
# Style 2
def abc(*args, **kwargs):
return myFunction(*args, **kwargs)
def myFunction(x):
print x
You can declare functions that use forward declarations, but Python executes the code in your source from top to bottom. So, this would compile and run:
def foo():
print "in foo"
bar()
def bar():
print "in bar"
foo()
foo()
(except it would cause a stack overflow at runtime, of course). In your example, Python is executing the line
abc = myFunction
before myFunction
is defined as anything. You could think of this in terms of typing your source code interactively into the interpreter. When you type in your assignment, you wouldn't have even typed in the definition of myFunction
yet, so Python wouldn't be able to refer to it.
Another way to look at this might be the following:
>>> myFunction = "hello"
>>> abc = myFunction
>>> def myFunction():
... print "there"
...
>>> abc
'hello'
>>> myFunction
<function myFunction at 0x63270>
>>> myFunction()
there
As you can see, the definition of the myFunction
function just changes the binding of the symbol myFunction
to a function object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With