def is_valid(s):
You're not giving us many hints, there.
What is s
?
What kind of validity criteria?
As an engineer, why would I want to call this function?
This function is crying out for a helpful """docstring""".
Consider using a longer name: is_valid_foo
(I do not yet know what "foo" might be.)
Consider adding an optional type annotation: s: str
.
May as well end with ...(s: str) -> bool:
while
you're at it, though the helpful is_
prefix
already tells us the return type.
Just like i
and j
are often good choices for local
variables that are indexes, s
can be a good choice
for a string.
But here s
is part of your public API,
so the documentation burden is much higher.
The function name didn't spell it out,
so the parameter name should definitely offer
at least one word's worth of hint.
# Length between 2 and 6
if length < 2 or length > 6:
Delete the # comment, as it doesn't tell us anything
beyond what the code has already said.
We use comments to describe the "why",
and code to describe the "how".
Consider chaining the comparisons:
if not(2 <= length <= 6):
I've used 'return False' 5 times
That's not so bad.
You have slightly complex rules, and the code is clear.
Here is one idea to help with clarity.
Express the rules in the positive rather than the negative,
breaking out a helper function for each one,
and string them together as conjuncts:
def starts_with_alpha(s: str) -> bool:
return s[:2].isalpha()
def is_valid(s: str) -> bool:
return (is_valid_length(s)
and s.isalnum()
and starts_with_alpha(s)
and is_alpha_then_number(s))
The idea is to make it read like an English sentence,
so there's little or no need for comments.
You didn't offer any requirements in English,
but they are apparent from the code.
Another approach to satisfying the requirements
would be to express them as a regex:
import re
valid_re = re.compile(r'^[a-z]{2,}(?P<num>([1-9]\d*)?)$')
...
return (is_valid_length(s)
and valid_re.search(s.lower()))
The code as written is clear and achieves its design goals.
I would be happy to delegate or accept maintenance tasks for it.
Before merging it down to main
the signature / docstring should be improved,
so maintenance engineers can immediately
see what the function is good for
without reading through all of its code.