I'm new to programming, I'd like you to check my work and criticize the hell out of me. What would you do differently?
FQDN: https://en.m.wikipedia.org/wiki/Fully_qualified_domain_name
- 253 characters not including trailing dot
- Label1.Label2.Label3.adomain.com
- All labels must be between 1-63 characters
- Cannot start or end with hyphen (-)
- May contain only a-z, 0-9 and hyphens
This just checks to make sure the hostname passed as an argument meets all standards.
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])?$', 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
I declared the variable for the regex pattern after the 2 conditionals with return statements. My thought was, why store a variable that would be unused if the prior conditions were met?
Could the regex be written any better?
try
block is really necessary. If you have unit tests, you should add them to your question. And if you don't have any tests, just provide a list of names and whether each of them is valid or not. \$\endgroup\$