lsst.daf.persistence  13.0-41-g024c5b6
utils.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 #
4 # LSST Data Management System
5 # Copyright 2016 LSST Corporation.
6 #
7 # This product includes software developed by the
8 # LSST Project (http://www.lsst.org/).
9 #
10 # This program is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the LSST License Statement and
21 # the GNU General Public License along with this program. If not,
22 # see <http://www.lsstcorp.org/LegalNotices/>.
23 #
24 from past.builtins import basestring
25 
26 try:
27  from collections.abc import Sequence, Set, Mapping
28 except ImportError:
29  from collections import Sequence, Set, Mapping
30 
31 
32 # -*- python -*-
33 
34 def listify(x):
35  """Takes any object and puts that whole object in a list:
36  - strings will be made into a single element in the list
37  - tuples will be converted to list
38  - lists will remain as lists
39  - None will be made into an empty list
40  """
41  if x is None:
42  x = []
43  elif isinstance(x, basestring):
44  x = [x]
45  elif isinstance(x, dict):
46  x = [x]
47  elif hasattr(x, '__iter__'):
48  x = list(x)
49  else:
50  x = [x]
51  return x
52 
53 
54 def iterify(x):
55  """Takes any object. Returns it if it is iterable. If it
56  is not iterable it puts the object in a list and returns
57  the list. None will return an empty list. If a new list
58  is always required use listify(). Strings will be placed
59  in a list with a single element.
60  """
61  if x is None:
62  x = []
63  elif isinstance(x, basestring):
64  x = [x]
65  elif hasattr(x, '__iter__'):
66  pass
67  else:
68  x = [x]
69  return x
70 
71 
72 def sequencify(x):
73  """Takes an object, if it is a sequence return it,
74  else put it in a tuple. Strings are not sequences.
75  If x is a dict, returns a sorted tuple of keys."""
76  if isinstance(x, (Sequence, Set)) and not isinstance(x, basestring):
77  pass
78  elif isinstance(x, Mapping):
79  x = tuple(sorted(x.keys()))
80  else:
81  x = (x, )
82  return x
83 
84 
85 def setify(x):
86  """Take an object x and return it in a set.
87 
88  If x is a container, will create a set from the contents of the container.
89  If x is an object, will create a set with a single item in it.
90  If x is a string, will treat the string as a single object (i.e. not as a list of chars)"""
91  if x is None:
92  x = set()
93 
94  # Here we have to explicity for strings because the set initializer will use each character in a string as
95  # a separate element. We cannot use the braces initialization because x might be a list, and we do not
96  # want the list to be an item; we want each item in the list to be represented by an item in the set.
97  # Then, we have to fall back to braces init because if the item is NOT a list then the set initializer
98  # won't take it.
99  if isinstance(x, basestring):
100  x = set([x])
101  else:
102  try:
103  x = set(x)
104  except TypeError:
105  x = set([x])
106  return x
107 
108 
109 def doImport(pythonType):
110  """Import a python object given an importable string"""
111  try:
112  if not isinstance(pythonType, basestring):
113  raise TypeError("Unhandled type of pythonType, val:%s" % pythonType)
114  # import this pythonType dynamically
115  # pythonType is sometimes unicode with Python 2 and pybind11; this breaks the interpreter
116  pythonTypeTokenList = str(pythonType).split('.')
117  importClassString = pythonTypeTokenList.pop()
118  importClassString = importClassString.strip()
119  importPackage = ".".join(pythonTypeTokenList)
120  importType = __import__(importPackage, globals(), locals(), [importClassString], 0)
121  pythonType = getattr(importType, importClassString)
122  return pythonType
123  except ImportError:
124  pass
125  # maybe python type is a member function, in the form: path.to.object.Class.funcname
126  pythonTypeTokenList = pythonType.split('.')
127  importClassString = '.'.join(pythonTypeTokenList[0:-1])
128  importedClass = doImport(importClassString)
129  pythonType = getattr(importedClass, pythonTypeTokenList[-1])
130  return pythonType
def doImport(pythonType)
Definition: utils.py:109