Unsubscriptable object when using Exec

Chris Rebert clp at rebertia.com
Fri Nov 14 19:01:28 EST 2008


On Fri, Nov 14, 2008 at 10:40 AM, Indian <write2abdul at gmail.com> wrote:
> Hi Friends
>
> I'm getting the TypeError Unsubscriptable object when using Exec in a class
>
> Here's the example
>
> class Fake(object):
>   def __init__(self, reg):
>     self._reg = reg
>
>   def OpenKey(self, rootkey, path):
>     open_key = self._reg
>     path_string='[\'HKLM\']'
>     for key in path.split('\\'):
>       path_string += '[\'%s\']'%key
>     a='d=open_key%s'%path_string
>     exec(a)
>     return d
>
> When i create a claassobject and call the method Openkey i get the above
> error but it works fine in the below example without class
>
> def OpenKey(rootkey, path, reg):
>   open_key = reg
>   path_string='[\'HKLM\']'
>   for key in path.split('\\'):
>     path_string += '[\'%s\']'%key
>   a='d=open_key%s'%path_string
>   print a
>   exec(a)
>   return d

You don't need and shouldn't be using `exec` here. It appears as
though you're just doing the following in a much more obtuse and
unnecessarily complicated manner:

def OpenKey(rootkey, path, reg):
    open_key = reg['HKLM']
    for key in path.split('\\'):
        open_key = open_key[key]
    return open_key

Lesson: Don't use `exec`.
More importantly, what led you to think you needed to use it here in
the first place?

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> What am i doing wrong in the class?Any thought on this would be helpful :)
>
> Thanks in Advance
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list