ATLAS Offline Software
Control/StoreGateBindings/python/Bindings.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2023 CERN for the benefit of the ATLAS collaboration
2 
3 # @file: StoreGateBindings/python/Bindings.py
4 # @author: Wim Lavrijsen <WLavrijsen@lbl.gov>
5 # @author: Sebastien Binet <binet@cern.ch>
6 
7 from __future__ import print_function
8 
9 
10 __author__ = """
11 Wim Lavrijsen (WLavrijsen@lbl.gov),
12 Sebastien Binet (binet@cern.ch)
13 """
14 
15 
16 def _setup():
17  import cppyy
18  # StoreGate bindings from dictionary
19  cppyy.load_library( "libAthenaPythonDict" ) # for clidsvc
20  cppyy.load_library( "libStoreGateBindingsDict" ) # for storegatesvc
21  cppyy.load_library( "libStoreGateBindings" ) # not linked from libStoreGateBindingsDict in ROOT6
22 
23  global py_retrieve
24  py_retrieve = cppyy.gbl.AthenaInternal.retrieveObjectFromStore
25 
26  global py_record
27  py_record = cppyy.gbl.AthenaInternal.recordObjectToStore
28 
29  global py_sg_contains
30  py_sg_contains = cppyy.gbl.AthenaInternal.py_sg_contains
31 
32  global py_sg_getitem
33  py_sg_getitem = cppyy.gbl.AthenaInternal.py_sg_getitem
34 
35  # retrieve the StoreGateSvc class
36  global StoreGateSvc
37  StoreGateSvc = cppyy.gbl.StoreGateSvc
38 
39  # add specialized retrieve method
40  def retrieve( self, klass, key = None ):
41  ret = py_retrieve( self, klass, key )
42  if ret and hasattr(ret,'setStore') and not ret.hasStore():
43  if not hasattr(ret,'trackIndices') or ret.trackIndices():
44  if py_sg_contains (self, 'SG::IConstAuxStore', key + 'Aux.'):
45  aux = py_retrieve (self, 'SG::IConstAuxStore', key + 'Aux.')
46  ret.setStore (aux)
47  return ret
48  StoreGateSvc.retrieve = retrieve
49 
50  # add specialized record method
51  def record( self, obj, key, allowMods=True, resetOnly=True, noHist=False ):
52  return py_record( self, obj, key, allowMods, resetOnly, noHist )
53  StoreGateSvc.record = record
54 
55  # add specialized contains method
56  def contains( self, klass_or_clid, key ):
57  from builtins import int
58  if isinstance(klass_or_clid, str):
59  try:
60  clid = int(klass_or_clid)
61  klass = self._pyclidsvc.typename(clid)
62  except ValueError:
63  klass = str(klass_or_clid)
64  pass
65  elif isinstance(klass_or_clid, int):
66  klass = self._pyclidsvc.typename(klass_or_clid)
67  elif isinstance(klass_or_clid, type):
68  klass = klass_or_clid.__name__
69  else:
70  raise TypeError(
71  'argument 2 must be a typename, a clid or a type (got %r)' %
72  type(klass_or_clid))
73  return py_sg_contains( self, klass, key )
74  StoreGateSvc.contains = contains
75 
76  # dict-pythonization of storegate: __setitem__
77  def __setitem__ (self, key, obj):
78  return py_record( self, obj, key, True, True, False )
79  StoreGateSvc.__setitem__ = __setitem__
80 
81  # dict-pythonization of storegate: __getitem__
82  def __getitem__ (self, key):
83  try:
84  ret = py_sg_getitem(self, key)
85  except LookupError as err:
86  raise KeyError(str(err))
87  if ret and hasattr(ret,'setStore') and hasattr(ret,'hasStore') and not ret.hasStore():
88  if not hasattr(ret,'trackIndices') or ret.trackIndices():
89  if py_sg_contains (self, 'SG::IConstAuxStore', key + 'Aux.'):
90  aux = py_retrieve (self, 'SG::IConstAuxStore', key + 'Aux.')
91  ret.setStore (aux)
92  return ret
93  StoreGateSvc.__getitem__ = __getitem__
94 
95  # dict-pythonization of storegate: __len__
96  def __len__ (self):
97  return len(self.keys())
98  StoreGateSvc.__len__ = __len__
99 
100  # make dump print, rather than return string
101  def dump(self, fd = None):
102  if fd is None:
103  import sys
104  fd = sys.stdout
105  print (self.__class__._dump( self ), file=fd)
106  StoreGateSvc._dump = StoreGateSvc.dump
107  StoreGateSvc.dump = dump
108 
109  # allow the use of the pythonized properties interface
110  def __getattr__( self, attr ):
111  try: from GaudiPython.Bindings import iProperty
112  except ImportError: from gaudimodule import iProperty
113  return getattr( iProperty("StoreGateSvc", self), attr )
114 
115  def __setattr__( self, attr, value ):
116  try: from GaudiPython.Bindings import iProperty
117  except ImportError: from gaudimodule import iProperty
118  return setattr( iProperty("StoreGateSvc", self), attr, value )
119 
120  StoreGateSvc.__getattr__ = __getattr__
121  StoreGateSvc.__setattr__ = __setattr__
122 
123  import AthenaPython.PyAthena as PyAthena
124  StoreGateSvc._pyclidsvc = PyAthena.py_svc('ClassIDSvc')
125 
126  def keys(self, clid=None, allKeys=False):
127  """return the list of keys for a given CLID (int, type or class_name)
128  if clid is None, it will return the list of all keys.
129  When 'allKeys' is True it will also return the key aliases.
130  """
131  if isinstance(clid, str):
132  clid = self._pyclidsvc.clid(clid)
133  if isinstance(clid, type):
134  clid = self._pyclidsvc.clid(clid.__name__)
135  if clid is None:
136  return [p.name() for p in self.proxies()]
137  return [str(x) for x in self._cpp_keys(clid, allKeys)]
138  StoreGateSvc._cpp_keys = StoreGateSvc.keys
139  StoreGateSvc.keys = keys
140 
141 
142  #The cppyy version that comes with ROOT v6.22 checks also __len__!=0
143  #when casting to bool. Since we defined a __len__ method, newly-created
144  #(empty) StoreGate instances are always casted to False and therefore
145  #considered invalid.
146  #Work-around by implementing our own __bool__ method
147  StoreGateSvc.__bool__ = lambda self : True
148 
149  return
150 
151 
152 _setup()
153 
154 
155 del _setup
python.PyKernel.retrieve
def retrieve(aClass, aKey=None)
Definition: PyKernel.py:110
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
python.Bindings._setup
def _setup()
initialize the bindings' registration
Definition: Control/AthenaPython/python/Bindings.py:818
AthenaInternal::py_sg_contains
PyObject * py_sg_contains(PyObject *storeGateSvc, PyObject *tp, PyObject *key)
Definition: StoreGatePyExt.cxx:346
contains
bool contains(const std::string &s, const std::string &regx)
does a string contain the substring
Definition: hcg.cxx:111
AthenaInternal::py_sg_getitem
PyObject * py_sg_getitem(PyObject *storeGateSvc, PyObject *key)
Definition: StoreGatePyExt.cxx:414
python.Dumpers.typename
def typename(t)
Definition: Dumpers.py:194
python.CaloScaleNoiseConfig.type
type
Definition: CaloScaleNoiseConfig.py:78
python.Bindings.__setitem__
__setitem__
Definition: Control/AthenaPython/python/Bindings.py:763
str
Definition: BTagTrackIpAccessor.cxx:11
python.Bindings.keys
keys
Definition: Control/AthenaPython/python/Bindings.py:790
python.PyAthenaComps.__setattr__
__setattr__
Definition: PyAthenaComps.py:41
python.Bindings.__getitem__
__getitem__
Definition: Control/AthenaPython/python/Bindings.py:771
FourMomUtils::dump
std::ostream & dump(std::ostream &out, const I4MomIter iBeg, const I4MomIter iEnd)
Helper to stream out a range of I4Momentum objects.
Definition: P4Dumper.h:24