def escape_dn_for_filter(anything: str) -> str:
    """Escape an LDAP distinguished name so that it can be used in filters without confusing the server.
    Distinguished names already have some special characters escaped or encoded, so we must use this
    function instead of the generic escape function, which would escape the existing escape sequences.

    In a filter, you use the format field=value.
    But distinguished names are in the form CN=x,OU=y,DC=z so those equal signs need to be escaped.
    But then the values x, y, and z can also have equal signs in them, and those will ALREADY be escaped
    differently from the ones following CN, OU, etc.
    That's why DNs need a different escaping in filters than everything else.
    """
    if isinstance(anything, int) or isinstance(anything, float):
        return anything

    if anything.isalnum():
        return anything

    def escape_char(char):
        """ Escape a single character."""
        if char in "()*":
            return "\\%02x" % ord(char)
        else:
            return char
    return "".join(escape_char(x) for x in anything)