开发者

Python: NameError while using nested classes

开发者 https://www.devze.com 2023-02-25 11:48 出处:网络
I encountered with the following error: NameError: name \'JsonCleaner\' is not defined The line, causing the error is the first pair in dictionary 开发者_开发知识库ERROR_CODES_MAPPING_DICT (see cod

I encountered with the following error:

NameError: name 'JsonCleaner' is not defined

The line, causing the error is the first pair in dictionary 开发者_开发知识库ERROR_CODES_MAPPING_DICT (see code below):

from sshop.engine.models import WrongJsonError

class JsonCleaner:


    class NormalizeError(Exception):

        ERROR_NO_CODE = 0
        ERROR_TYPE_MISMATCH = 1
        ERROR_WRONG_VALUE = 2
        ERROR_LACK_OF_FIELD = 3

        def __init__(self, error_desc, error_code=ERROR_NO_CODE):
            self.error_desc = error_desc
            self.error_code = error_code

        def __unicode__(self):
            return repr(self.error_desc)


    # .... some methods ........


    ERROR_CODES_MAPPING_DICT = {
        # Line where exception is raised:
        JsonCleaner.NormalizeError.ERROR_NO_CODE:       WrongJsonError.NO_ERROR, 
        JsonCleaner.NormalizeError.ERROR_LACK_OF_FIELD: WrongJsonError.ERROR_LACK_OF_FIELD,
        JsonCleaner.NormalizeError.ERROR_TYPE_MISMATCH: WrongJsonError.ERROR_TYPE_MISMATCH,
        JsonCleaner.NormalizeError.ERROR_WRONG_VALUE:   WrongJsonError.ERROR_WRONG_VALUE, 
    }

What am I doing wrong?


The class name cannot be used within the class scope since the name isn't actually bound until the class is completely defined. Move the dict literal outside the class scope.

JsonCleaner.ERROR_CODES_MAPPING_DICT = ...


JsonCleaner ist not completely defined at that point and therefor unknown. Just remove it and use NormalizeError.ERROR_NO_CODE and it should work.


Try replacing "JsonCleaner" with "self".

 ERROR_CODES_MAPPING_DICT = {
    # Line where exception is raised:
    self.NormalizeError.ERROR_NO_CODE:       WrongJsonError.NO_ERROR, 
    self.NormalizeError.ERROR_LACK_OF_FIELD: WrongJsonError.ERROR_LACK_OF_FIELD,
    self.NormalizeError.ERROR_TYPE_MISMATCH: WrongJsonError.ERROR_TYPE_MISMATCH,
    self.NormalizeError.ERROR_WRONG_VALUE:   WrongJsonError.ERROR_WRONG_VALUE, 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消