Task

Demonstrate the different syntax and semantics provided for calling a function.



This may include:

   Calling a function that requires no arguments
   Calling a function with a fixed number of arguments
   Calling a function with optional arguments
   Calling a function with a variable number of arguments
   Calling a function with named arguments
   Using a function in statement context
   Using a function in first-class context within an expression
   Obtaining the return value of a function
   Distinguishing built-in functions and user-defined functions
   Distinguishing subroutines and functions
   Stating whether arguments are passed by value or by reference
   Is partial application possible and how


This task is not about defining functions.




def no_args():
    pass
# call
no_args()
 
def fixed_args(x, y):
    print('x=%r, y=%r' % (x, y))
# call
fixed_args(1, 2)        # x=1, y=2
 
## Can also called them using the parameter names, in either order:
fixed_args(y=2, x=1)
 
## Can also "apply" fixed_args() to a sequence:
myargs=(1,2) # tuple
fixed_args(*myargs)
 
def opt_args(x=1):
    print(x)
# calls
opt_args()              # 1
opt_args(3.141)         # 3.141
 
def var_args(*v):
    print(v)
# calls	
var_args(1, 2, 3)       # (1, 2, 3)
var_args(1, (2,3))      # (1, (2, 3))
var_args()              # ()
 
## Named arguments
fixed_args(y=2, x=1)    # x=1, y=2
 
## As a statement
if 1:
    no_args()
 
## First-class within an expression
assert no_args() is None
 
def return_something():
    return 1
x = return_something()
 
def is_builtin(x):
	print(x.__name__ in dir(__builtins__))
# calls
is_builtin(pow)         # True
is_builtin(is_builtin)  # False
 
# Very liberal function definition
 
def takes_anything(*args, **kwargs):
    for each in args:
        print(each)
    for key, value in sorted(kwargs.items()):
        print("%s:%s" % (key, value))
    # Passing those to another, wrapped, function:
    wrapped_fn(*args, **kwargs)
    # (Function being wrapped can have any parameter list
    # ... that doesn't have to match this prototype)
 
## A subroutine is merely a function that has no explicit
## return statement and will return None.
 
## Python uses "Call by Object Reference".
## See, for example, http://www.python-course.eu/passing_arguments.php
 
## For partial function application see:
##   http://rosettacode.org/wiki/Partial_function_application#Python