1

I have to write a lot of Python code which will look like the following:

class MyClass(object):
    ...
    ...
    ...
    def handle_request(self, request):
        attr1 = self.__get_attr1(request)
        self.__validate_attr1(attr1)

        attr2 = self.__get_attr2(request)
        self.__validate_attr2(attr2)

        attr3 = self.__get_attr3(request)
        self.__validate_attr1(attr3)
        ...
        ...
        ...
        attrn = self.__get_attrn(request)
        self.__validate_attrn(attr1)

To make my life easier I thought I could do the following:

class MyClass(object):
    ...
    ...
    ...
    def handle_request(self, request):
        attr_list = ('attr1', 'attr2', 'attr3', ..., 'attrn');
        for a in attr_list:
            locals()[a] = eval('self.__get_{}(request)'.format(a))
            eval('self.__validate_{}'.format(a)

However when I run this code I'm getting a following error:

AttributeError: 'MyClass' object has no attribute '__get_attr1'

Clearly I'm missing something big but I'm not sure what exactly.

8
  • You clearly haven't defined the value of __get_attr1 before using it. Commented Dec 11, 2016 at 4:21
  • @ÉbeIsaac assume __get_attr methods are defined. Commented Dec 11, 2016 at 4:29
  • I may, but too bad your program couldn't do the same. Could you access __get_attr1 by any other means outside eval? Commented Dec 11, 2016 at 4:31
  • @ÉbeIsaac What do you mean by other means? Commented Dec 11, 2016 at 4:44
  • Like simply printing it before using eval, print(self.__get_attr1) Commented Dec 11, 2016 at 4:46

1 Answer 1

1

To answer the question you didn't ask, instead of using eval, you might try something like

class MyClass(object):
    ...
    def __init__(self):
        self.attr_list = [self.__get_attr1, ..., self.__get_attrn]
        self.validate_list = [self.__validate_attr1, ..., self.__validate_attrn]
    ...
    def handle_request(self, request):
        attrs = [get(request) for get in self.attr_list]
        for validate in self.validate_list:
            validate(request)
Sign up to request clarification or add additional context in comments.

1 Comment

Or just getattr(self, attribute_name).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.