python / python/cpython

Improving conciseness of ipaddress factory functions.

Aberta
#93,880 0 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

stdlib type-feature
Linguagem predominante
Python
Estrelas
77.2k
Forks
36k
Merge médio
1d 9h
PRs com merge (30d)
558

Descrição

Suggestion to refactor the 3 factory functions ip_address, ip_network, ip_interface.
In addition making a similar modification in the _prefix_from_ip_string function.

Currently the functions contain code which can be improved in terms of conciseness and extendability.

  • try/catch containing a pass statement can be substituted with contextlib.suppress making the code more concise
  • we can use a for loop which will iterate over the class objects to further increase conciseness

Current factory function implementations (docstrings not included for brevity)

def ip_address(address):
    try:
        return IPv4Address(address)
    except (AddressValueError, NetmaskValueError):
        pass

    try:
        return IPv6Address(address)
    except (AddressValueError, NetmaskValueError):
        pass

    raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 address')


def ip_network(address, strict=True):
    try:
        return IPv4Network(address, strict)
    except (AddressValueError, NetmaskValueError):
        pass

    try:
        return IPv6Network(address, strict)
    except (AddressValueError, NetmaskValueError):
        pass

    raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 network')


def ip_interface(address):
    try:
        return IPv4Interface(address)
    except (AddressValueError, NetmaskValueError):
        pass

    try:
        return IPv6Interface(address)
    except (AddressValueError, NetmaskValueError):
        pass

    raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 interface')

Proposed function implementations

def ip_address(address):
    for ip_class in [IPv4Address, IPv6Address]:
        with contextlib.suppress(AddressValueError, NetmaskValueError):
            return ip_class(address)

    raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 address')


def ip_network(address, strict=True):
    for network_class in [IPv4Network, IPv6Network]:
        with contextlib.suppress(AddressValueError, NetmaskValueError):
            return network_class(address, strict)

    raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 network')


def ip_interface(address):
    for ip_interface_class in [IPv4Interface, IPv6Interface]:
        with contextlib.suppress(AddressValueError, NetmaskValueError):
            return ip_interface_class(address)

    raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 interface')

current _prefix_from_ip_string function (docstrings and comments not included for brevity)

    @classmethod
    def _prefix_from_ip_string(cls, ip_str):
        try:
            ip_int = cls._ip_int_from_string(ip_str)
        except AddressValueError:
            cls._report_invalid_netmask(ip_str)

        try:
            return cls._prefix_from_ip_int(ip_int)
        except ValueError:
            pass

        ip_int ^= cls._ALL_ONES
        try:
            return cls._prefix_from_ip_int(ip_int)
        except ValueError:
            cls._report_invalid_netmask(ip_str)

Suggested improvement

    @classmethod
    def _prefix_from_ip_string(cls, ip_str):
        try:
            ip_int = cls._ip_int_from_string(ip_str)
        except AddressValueError:
            cls._report_invalid_netmask(ip_str)

        with contextlib.suppress(ValueError):
            return cls._prefix_from_ip_int(ip_int)

        ip_int ^= cls._ALL_ONES
        try:
            return cls._prefix_from_ip_int(ip_int)
        except ValueError:
            cls._report_invalid_netmask(ip_str)

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Localize os pontos de entrada ip_address, ip_network, ip_interface e _prefix_from_ip_string na implementação de ipaddress e, em seguida, leia o tratamento de exceções ao redor deles. Compare as alterações propostas no loop e na supressão com o comportamento atual, incluindo os caminhos de erro existentes, e verifique se os testes relevantes de ipaddress continuam passando.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
python
Domínio
networking
Tipo de issue
Refatoração
Dificuldade
3/5
Tempo estimado
1-2 dias
Status de atividade
Estagnada
Clareza
Razoavelmente clara
Facilidade para iniciantes
35/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.