Как получить Python isidentifer() в Python 2.6?

Python 3 имеет строковый метод str.isidentifier

Как я могу получить аналогичную функциональность в Python 2.6, не переписывая собственное регулярное выражение и т.д.?

Ответы

Ответ 1

модуль tokenize определяет регулярное выражение, называемое Name

import re, tokenize, keyword
re.match(tokenize.Name + '$', somestr) and not keyword.iskeyword(somestr)

Ответ 2

re.match(r'[a-z_]\w*$', s, re.I)

должен делать красиво. Насколько я знаю, нет встроенного метода.

Ответ 3

В Python < 3.0 это довольно просто, так как вы не можете иметь символы Unicode в идентификаторах. Это должно сделать работу:

import re
import keyword

def isidentifier(s):
    if s in keyword.kwlist:
        return False
    return re.match(r'^[a-z_][a-z0-9_]*$', s, re.I) is not None

Ответ 4

Хорошие ответы до сих пор. Я бы написал это так.

import keyword
import re

def isidentifier(candidate):
    "Is the candidate string an identifier in Python 2.x"
    is_not_keyword = candidate not in keyword.kwlist
    pattern = re.compile(r'^[a-z_][a-z0-9_]*$', re.I)
    matches_pattern = bool(pattern.match(candidate))
    return is_not_keyword and matches_pattern

Ответ 5

Я решил сделать еще одну попытку, так как было несколько хороших предложений. Я попытаюсь их консолидировать. Следующие могут быть сохранены как модуль Python и запускаться непосредственно из командной строки. Если он запущен, он проверяет функцию, так что это доказуемо правильно (по крайней мере, в той мере, в какой документация демонстрирует возможность).

import keyword
import re
import tokenize

def isidentifier(candidate):
    """
    Is the candidate string an identifier in Python 2.x
    Return true if candidate is an identifier.
    Return false if candidate is a string, but not an identifier.
    Raises TypeError when candidate is not a string.

    >>> isidentifier('foo')
    True

    >>> isidentifier('print')
    False

    >>> isidentifier('Print')
    True

    >>> isidentifier(u'Unicode_type_ok')
    True

    # unicode symbols are not allowed, though.
    >>> isidentifier(u'Unicode_content_\u00a9')
    False

    >>> isidentifier('not')
    False

    >>> isidentifier('re')
    True

    >>> isidentifier(object)
    Traceback (most recent call last):
    ...
    TypeError: expected string or buffer
    """
    # test if candidate is a keyword
    is_not_keyword = candidate not in keyword.kwlist
    # create a pattern based on tokenize.Name
    pattern_text = '^{tokenize.Name}$'.format(**globals())
    # compile the pattern
    pattern = re.compile(pattern_text)
    # test whether the pattern matches
    matches_pattern = bool(pattern.match(candidate))
    # return true only if the candidate is not a keyword and the pattern matches
    return is_not_keyword and matches_pattern

def test():
    import unittest
    import doctest
    suite = unittest.TestSuite()
    suite.addTest(doctest.DocTestSuite())
    runner = unittest.TextTestRunner()
    runner.run(suite)

if __name__ == '__main__':
    test()

Ответ 6

Что я использую:

def is_valid_keyword_arg(k):
    """
    Return True if the string k can be used as the name of a valid
    Python keyword argument, otherwise return False.
    """
    # Don't allow python reserved words as arg names
    if k in keyword.kwlist:
        return False
    return re.match('^' + tokenize.Name + '$', k) is not None

Ответ 7

Все предлагаемые решения пока не поддерживают Unicode или разрешают число в первом char при запуске на Python 3.

Изменить: предлагаемые решения должны использоваться только на Python 2, а на Python3 isidentifier следует использовать. Вот решение, которое должно работать где угодно:

re.match(r'^\w+$', name, re.UNICODE) and not name[0].isdigit()

В основном, он проверяет, состоит ли что-то (не менее 1) символов (включая числа), а затем проверяет, что первый char не является числом.