I saw the following code:
eris = lambda:None
eris.jkcpp = np.einsum('iipq->ipq', eriaa[:ncore[0],:ncore[0],:,:])
eris.jc_PP = np.einsum('iipq->pq', eriab[:ncore[0],:ncore[0],:,:])
Can we define arbitrary attributes for a function defined by lambda:None
?
I was reading a casscf code, which is an algorithm in quantum chemistry, and the author used this lambda function to get the 2-electron integrals. And then decided against it, apparently.
This looks like a trick to create a simple object to hold values in one line. Most built-in objects don't allow you to set arbitrary attributes on them:
>>> object().x = 0
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'object' object has no attribute 'x'
>>> ''.x = 0
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'x'
>>> [].x = 0
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'list' object has no attribute 'x'
If you make your own class, then you can add whatever attributes you want. In this case you could make a class whose __init__
method assigns the attributes, but this may not be worth the boilerplate. So you can just make an empty class:
>>> class Data(object): pass
>>> d = Data()
>>> d.x = 0
>>> d.x
0
Apparently the programmer is either not aware of this or doesn't want that extra line where the class is declared and has come up with their own workaround for storing data. It turns out functions, despite being a built-in type do allow you to add attributes to them:
>>> def foo(): pass
>>> foo.x = 0
>>> foo.x
0
Both the above and a lambda let you create such a container in a single statement. I actually think that's a neat idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With