[ python-Bugs-1177811 ] Exec Inside A Function

SourceForge.net noreply at sourceforge.net
Wed Apr 6 16:30:41 CEST 2005


Bugs item #1177811, was opened at 2005-04-06 14:30
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1177811&group_id=5470

Category: Python Interpreter Core
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Andrew Wilkinson (andrew_j_w)
Assigned to: Nobody/Anonymous (nobody)
Summary: Exec Inside A Function

Initial Comment:
When 'exec'ing code that creates a function inside a function the 
defined function (fact in the example below) is created with the 
module level namespace as it's parent scope. 
 
The following should return 2 however it raises a NameError as fact 
is not defined. 
 
def f(): 
    exec """ 
def fact(x): 
    if x==1: 
        return 1 
    else: 
        return x*fact(x-1) 
""" 
    return fact 
 
f()(2) 
 
If you run following code... 
 
def f(): 
    exec """ 
def fact(x): 
    if x==1: 
        return 1 
    else: 
        return x*fact(x-1) 
""" in locals() 
    return fact 
 
... it works as expected. 
 
The documentation states that "In all cases, if the optional parts 
are omitted, the code is executed in the current scope." That is 
clearly not the case here as the 'fact' function is set with the 
module level scope as it's parent scope. 
 
It would appear to me that either this a documentation bug or a 
flaw in exec. I sincerely hope this a bug in exec and not the 
desired behaviour as it doesn't make any sense to me... 
 

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1177811&group_id=5470


More information about the Python-bugs-list mailing list