Pythonically check if a variable name is valid

后端 未结 6 2103
臣服心动
臣服心动 2020-12-29 07:37

tldr; see the final line; the rest is just preamble.


I am developing a test harness, which parses user scripts and generates a Python script which it then ru

6条回答
  •  甜味超标
    2020-12-29 08:00

    You can just let Python (works on any version in use today, as far as I know) do the check for you they way it normally would internally, and catch the exception:

    def _dummy_function_taking_kwargs(**_):
        pass
    
    try:
        _dummy_function_taking_kwargs(**{my_variable: None})
        # if the above line didn't raise and we get here,
        # the keyword/variable name was valid.
        # You could also replace the external dummy function
        # with an inline lambda function.
    except TypeError:
        # If we get here, it wasn't.
    

    Notably, TypeError is consistently raised whenever a dict undergoes keyword argument expansion and has a key which isn't a valid function argument, and whenever a dict literal is being constructed with an invalid key.

    The advantage over the accepted answer is that it is both compatible across both Python 3 and 2, and not as fragile as the ast.parse/compile approach (which would count strings like foo = bar; qux as valid).

    I haven't thoroughly audited this solution or written Hypothesis tests for it to fuzz it, so there might be some corner case, but it seems to generally work on Python 3.7, 3.6, 2.7, and 2.5 (not that anyone ought to be using 2.5 nowadays, but it's still out in the wild and you might be one of the few poor sods stuck having to write code that works with 2.6/2.5).

提交回复
热议问题