What is the best practice to do with temporary (unused) list?

I’ve a code snippet below which gets the dataclass variables (keys) with "_dg" prefix, then gets the attribute of each key according to declaration order and appends them into a list. At the end this will be merged into a single element and returned as a string.

def create_decrypted_EFSOD(self) -> str:

    _ = []
    try:
        for attr in list(self.__dict__.keys()):
            if attr.startswith("_dg"):
                _.append(self.__getattribute__(attr))

        return "".join(_)

    finally:
        del _ 

Where my dataclass is declared as:

@dataclass
class PassiveAuthenticator:
    """
    Passive Authentication of eMRTD Documents for Inspection Systems (IFD's). Protects against IC forging.

    Refers to "Doc. 9303, Machine Readable Travel Documents, Part 11 - Security Mechanisms for MRTDS" by ICAO, 2021,
    Section 6.1 and Appendix G for more details about security protocols.

    """
    _dg1: str
    _dg2: str
    _dg3: str
    .
    .
    

I know the _ variable always refers to last returned value, that is why I used it to avoid creating unnecessary variable, but creating a temporary variable still bothers me. What is the best practice for this situation?

Also, does deleting _ variable mean anything since it’ll be redeclared again? Since I’m a C++ dev it’s a habit to deallocate.

>Solution :

To repeat what was already said in the comments:

  • no, _ does not refer to the last returned variable
  • no, _ is not a good name for the variable, it should be used on variables that are unused but your variable is used
  • no, python has automatic GC and you do not need to explicitly del _.

Therefore your code should simply be

def create_decrypted_EFSOD(self) -> str:
    matching_attributes = []
    for attr in list(self.__dict__.keys()):
        if attr.startswith("_dg"):
            matching_attributes.append(self.__getattribute__(attr))

    return "".join(matching_attributes)

or simplified using a list comprehension

def create_decrypted_EFSOD(self) -> str:
    return "".join(value for attr, value in self.__dict__.items() if attr.startswith("_dg"))

Leave a Reply