我刚开始编程,我想让你检查一下我的工作,然后批评我。你会做什么不同的事?
FQDN:https://en.m.wikipedia.org/wiki/Fully_合资格_域名_名字
这只是检查作为参数传递的主机名是否符合所有标准。
import re
def is_fqdn(hostname):
"""
:param hostname: string
:return: bool
"""
# Remove trailing dot
try: # Is this necessary?
if hostname[-1] == '.':
hostname = hostname[0:-1]
except IndexError:
return False
# Check total length of hostname < 253
if len(hostname) > 253:
return False
# Split hostname into list of DNS labels
hostname = hostname.split('.')
# Define pattern of DNS label
# Can begin and end with a number or letter only
# Can contain hyphens, a-z, A-Z, 0-9
# 1 - 63 chars allowed
fqdn = re.compile(r'^[a-z0-9]([a-z-0-9-]{0,61}[a-z0-9])?我在带有返回语句的两个条件词之后声明了regex模式的变量。我的想法是,如果满足了先前的条件,为什么要存储一个未使用的变量?能写得更好吗?, re.IGNORECASE)
# Check if length of each DNS label < 63
# Match DNS label to pattern
for label in hostname:
if len(label) > 63:
return False
if not fqdn.match(label):
return False
# Found no errors, returning True
return True我在带有返回语句的两个条件词之后声明了regex模式的变量。我的想法是,如果满足了先前的条件,为什么要存储一个未使用的变量?
能写得更好吗?
发布于 2020-01-11 19:04:14
评论:
mypy-able。try/catch块只是间接要求参数至少有一个字符长的一种方法。更明确的是,IMO只需要显式地检查长度,特别是因为您已经在做下一步了。Union类型声明它)。在生成具有新类型的新对象时,只需使用新变量名即可。all函数比滚动您自己的for循环要好。import re
def is_fqdn(hostname: str) -> bool:
"""
https://en.m.wikipedia.org/wiki/Fully_qualified_domain_name
"""
if not 1 < len(hostname) < 253:
return False
# Remove trailing dot
if hostname[-1] == '.':
hostname = hostname[0:-1]
# Split hostname into list of DNS labels
labels = hostname.split('.')
# Define pattern of DNS label
# Can begin and end with a number or letter only
# Can contain hyphens, a-z, A-Z, 0-9
# 1 - 63 chars allowed
fqdn = re.compile(r'^[a-z0-9]([a-z-0-9-]{0,61}[a-z0-9])?我赞同罗兰关于编写单元测试的建议。这样的函数很容易编写测试;您可以这样做:def test_is_fqdn() -> None:
# Things that are FQDNs
assert is_fqdn("homestarrunner.net")
assert is_fqdn("zombo.com")
# Things that are not FQDNs
assert not is_fqdn("")
assert not is_fqdn("a*")
assert not is_fqdn("foo") # no TLD means it's not a FQDN!注意,测试中的最后一个断言将失败., re.IGNORECASE)
# Check that all labels match that pattern.
return all(fqdn.match(label) for label in labels)我赞同罗兰关于编写单元测试的建议。这样的函数很容易编写测试;您可以这样做:
A18
注意,测试中的最后一个断言将失败.
https://codereview.stackexchange.com/questions/235473
复制相似问题