17 Lexical Scoping
17.1 Lexical scoping
17.2 Data
Code
A = c(NA, 12, 15, 14, 18)
17.3 Error
Code
fn_mean(A, na.rm = TRUE)
Error in fn_mean(A, na.rm = TRUE): object 'xn' not found
17.4 No error due to lexical scoping
Code
xn = 1000
fn_mean(A, na.rm = TRUE)
[1] 0.059
17.5 Scoping rules
Python’s scoping rules are different from R’s, and Python does not have the same level of flexibility when it comes to capturing variables from external scopes.
Code
def fn_mean(x, **kwargs):
global xn
= kwargs.get('na_rm', None)
na_rm
if na_rm:
= x[~np.isnan(x)]
x
# xn = len(x)
= np.sum(x)
xsum = xsum / xn
xmean return xmean
# Example usage:
= 1000
xn = np.array([11, 12, np.nan, 14, 15])
A =y, na_rm=True) fn_mean(A, y