using execfile() in class/instance methods

Alex Martelli aleaxit at
Sat Dec 9 14:09:29 CET 2000

"Wayne Cuddy" <wcuddy at lserv.ja10629.home> wrote in message
news:slrn932qna.rtk.wcuddy at lserv.ja10629.home...
> I am attempting to use the execfile() function to "source" a file that
> has valid python code to create a diction object:
> bn { 'key' : 'value1',
>         'key2' : 'value2' }

This is not valid Python code -- it's probably missing an equal-sign
between the identified bn and the open-brace.

> I am issueing this command from a class constructor method and would
> like bn to be bound the class instance.  So in the future I can say:
>         print['key']

Piece of cake.

-- file: ba.txt
bn = { 'key' : 'value1',
     'key2' : 'value2' }
-- end of file: ba.txt

-- file:
class Ba:
    def bu(self):

ba = Ba()

-- end of file:



> Is this possible?  I assume I am screwing up the global() and locals()
> arguments to the function which I can say that I don't fully

I think it was probably just the missing '=' sign, as above.  The default
for globals and locals seem to be OK in this case.

> understand.  Also is there another better/worse way to do this???just
> so I can see what else is out there..

execfile is very risky if the textfile you're executing may contain
stuff, of course; then, you might want to build up the dictionary
in a safer manner, which might then be highly preferable.

But if the textfile is fully under your control, this might be quite OK.


More information about the Python-list mailing list