this is fine for user-entered expressionsbut what if we need to create function dynamicallyfor that we can use the built-in exec(function for examplethe user might give us formula such as and the name "area of sphere"which they want turned into function assuming that we replace with math pithe function they want can be created like thisimport math code ''def area_of_sphere( )return math pi * ''context {context["math"math exec(codecontextwe must use proper indentation--after allthe quoted code is standard python (although in this case we could have written it all on single line because the suite is just one line if exec(is called with some code as its only argument there is no way to access any functions or variables that are created as result of the code being executed furthermoreexec(cannot access any imported modules or any of the variablesfunctionsor other objects that are in scope at the point of the call both of these problems can be solved by passing dictionary as the second argument the dictionary provides place where object references can be kept for accessing after the exec(call has finished for examplethe use of the context dictionary means that after the exec(callthe dictionary has an object reference to the area_of_sphere(function that was created by exec(in this example we needed exec(to be able to access the math moduleso we inserted an item into the context dictionary whose key is the module' name and whose value is an object reference to the corresponding module object this ensures that inside the exec(callmath pi is accessible in some cases it is convenient to provide the entire global context to exec(this can be done by passing the dictionary returned by the globals(function one disadvantage of this approach is that any objects created in the exec(call would be added to the global dictionary solution is to copy the global context into dictionaryfor examplecontext globals(copy(this still gives exec(access to imported modules and the variables and other objects that are in scopeand because we have copiedany changes to the context made inside the exec(call are kept in the context dictionary and are not propagated to the global environment (it would appear to be more secure to use copy deepcopy()but if security is concern it is best to avoid exec(altogether we can also pass the local contextfor exampleby passing locals(as third argument--this makes objects in the local scope accessible to the code executed by exec(