File: util.py

package info (click to toggle)
python-urwid-utils 0.1.3.dev0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 132 kB
  • sloc: python: 516; makefile: 3
file content (41 lines) | stat: -rw-r--r-- 990 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# -*- coding: utf-8 -*-

import re

CONST_NAME_CRE = re.compile(r'^[A-Z][A-Z0-9_]+$')

def is_valid_identifier(name):
    """Pedantic yet imperfect. Test to see if "name" is a valid python identifier
    """
    if not isinstance(name, str):
        return False
    if '\n' in name:
        return False
    if name.strip() != name:
        return False
    try:
        code = compile('\n{0}=None'.format(name), filename='<string>', mode='single')
        exec(code)
        return True
    except SyntaxError:
        return False


def get_const_identifiers(*args):
    dargs = []
    for arg in args:
        try:
            dargs.append(dict(arg))
        except TypeError:
            dargs.append(vars(arg))

    const = {}
    for item in dargs:
        for name, value in item.items():
            if not CONST_NAME_CRE.match(name):
                continue
            if not is_valid_identifier(name):
                continue
            const[name] = value

    return const