0

I did find this solution, but he is trying to sanitize the name, I just want to know if it's valid or not. And a regex solution doesn't fit my needs cause is a fragile solution and specifications may change and/or escape some edgy cases.

1 Answers1

1

A maintainable solution for me is build a class and check it with AST. If the language move forward, the package should move forward as well.

import ast
def is_valid_class_name(name):
    class_definition = f'class {name}: pass'
    try:
        ast.parse(class_definition)
    except Exception as e:
        return False
    return True

That's it.

The same trick could be applied to variable name, assignment, whatever you want to check if is valid in python. Using a template ( which in this case is class NAMEOFCLASS: pass')

titusfx
  • 1,896
  • 27
  • 36