1

(Check edit at the bottom of the post)

I have a Dict[str, str] that is defined outside a function. Then this function calls the dictionary, but python raises NameError exception.

Weird thing is that the exception is raised in normal execution or debug mode, but not in debug console (while stopped in debug mode).

Other weird behaviour is that the name that the NameError exception refers to is not the variable name that my code calls.

CODE:

from enum import Enum
from dataclasses import dataclass, field

class LimitOrderStatus(Enum):
    NEW = '0'


__status_value_to_str_map = {
    LimitOrderStatus.NEW.value: 'new',
}

@dataclass
class LimitOrderState:
    status: LimitOrderStatus = field(init=False, default=None) # This is an Enum type with string values
    unfilled_quantity: float = field(init=False, default=None)

    def __serializable_dict__(self) -> dict:
        str_status = __status_value_to_str_map[self.status.value] # this raises the NameError Exception
        result = {'status': str_status, 'unfilled': self.unfilled_quantity}
        return result

los = LimitOrderState()
los.status = LimitOrderStatus.NEW
print(los.__serializable_dict__())

EXCEPTION: (you can see the NameError calls _LimitOrderState__status_value_to_str_map, but name called is __status_value_to_str_map)

File "xxx.py", line yyy, in __serializable_dict__
    a = __status_value_to_str_map[self.status.value]
NameError: name '_LimitOrderState__status_value_to_str_map' is not defined

Already tried:

  • deleting all files in pycache folder.
  • adding global __status_value_to_str_map at the beginning of the function.

EDIT: FOUND SOLUTION: replace name 2 underscores by 1 underscore (__status_value_to_str_map -> _status_value_to_str_map). But I don't understand why

0 Answers0