on perhaps unloading modules?
Hope Rouselle
hrouselle at jevedi.com
Fri Aug 20 21:36:05 EDT 2021
Greg Ewing <greg.ewing at canterbury.ac.nz> writes:
> On 21/08/21 6:15 am, Hope Rouselle wrote:
>>>>> code()
>> 'def p():\n import math\n return math.e\n'
>>>>> exec(code())
>>>>> p
>> <function p at 0x0113F5D0>
>>>>> p()
>> 2.718281828459045
>
> Note that this pollutes the globals of the module that you're calling
> exec() from. For better isolation you can pass in an explicit globals
> dict:
>
> g = {}
> exec(code(), g)
> g['p']()
Oh! Now I understand how to use it! That's in fact what I was looking
for. I noticed it was polluting my environment and was thinking --- hm,
that's no good. Thank you.
So I believe I understand how to pollute their environment too. Say I
have a procedure called external that I'd like to make available to
them. It seems this is what I need to do.
--8<---------------cut here---------------start------------->8---
def external():
return "external"
def run():
s = """
def s(*args):
import math
return external(), math.e, args
"""
g = {}
exec(s, g)
g["external"] = external
return g
--8<---------------cut here---------------end--------------->8---
>>> student["s"](1, 2)
('external', 2.718281828459045, (1, 2))
That's good. So I can restrict their environment too, by removing some
built-ins and so on. (I wish I could restrict their syntax too, though,
but I fear that's not possible. For instance, it would be very useful
if I could remove loops. If the course doesn't let them use them, it is
silly to have to ask them kindly not to use them --- please be patient
with this poorly designed course. In reality there is a whole
department learning to run a course and there are many students helping
this department get a passing grade into how to do it.) :-D
Anyhow, your ideas have improved the outlook of this grader quite a lot.
Thank you!
More information about the Python-list
mailing list