1 """handy-dandy functions"""
2
3 import os.path
4 import itertools
5 import sys
6
8 """
9 @arg path: a filesystem path
10 @type path: string
11
12 @returns: a fully-expanded, normalized path
13 @rtype: string
14 """
15 return os.path.normpath(os.path.expanduser(os.path.expandvars(path)))
16
18 """splits a.b.c into (a.b, c)
19
20 @arg name: a dotted string
21 @type name: string
22
23 @rtype: 2-tuple
24 """
25 x=name.rfind(".")
26 return name[:x], name[x+1:]
27
29 """
30 @returns: python-style private name, like _cls__name
31 @rtype: String
32
33 @arg cls: class for which to privatize
34 @type cls: Class
35
36 @arg name: name of the private member variable. Should start with __
37 @type name: String
38 """
39 assert len(name)>=3 and name[:2]=='__', "name must start with '__'"
40 assert isinstance(cls, type), "cls must be a class"
41
42 return "_%s%s"%(cls.__name__, name)
43
45 """remove all items in dict d that are not in keys.
46
47 @arg d: the dict to prune
48 @type d: dict
49
50 @arg keys: keys to keep. If None, keep all keys
51 @type keys: set/tuple/list/dict
52
53 @returns: the modified d
54 """
55 if keys is not None:
56 for k in d.keys():
57 if k not in keys:
58 del d[k]
59
60 return d
61
62 __namecounter=itertools.count(1)
64 """return a decent name if none is provided
65
66 Generated names will be of the form 'thingtype-#'.
67
68 @arg name: a name. if None or empty, generate a new name
69 @type name: string or None
70
71 @arg thingtype: the type of thing of name. If None, and called inside a
72 class, use the class name.
73 @type thingtype: string
74 """
75 if name: return name
76
77 if thingtype is None:
78 frame=sys._getframe(1)
79 thingtype=frame.f_locals['self'].__class__.__name__
80
81 return "%s-%d"%(thingtype, __namecounter.next())
82