Short post! just ran into one python problem. Actually it is very simple task, not a problem at all, but I wanna write it in one line. So the idea is, I need a function to return the first value, that is true from the given callable checks. Looked up google and there is a module called: first but since it is just a practice of code, I don’t want to install a module just for that. So here is how it is done.
Let’s begin with Code.
next((x for x in seq if x), None)
So I took this from first module alternatives, and it is worth sharing. There are other methods as well, like using itertools which I don’t wanna import :p.
Anyway here is how it works. Normally you would just loop through and break the loop when you found first occurrence, Most Python’s magic came from iterable it is a mechanism so you doesn’t really need to go through the whole loop therefore free your execution resources. Method next will returns whatever your found on the top of the the iterable, in this case list (first argument), and if nothing is found it returns default value instead (second argument), if you don’t provide this it will raise exception instead, so I use None. Now the trick is you need to for it with a condition if x. And that’s it. Short and simple 🙂
My goal is to detect special attributes from my base classes, in my special metaclass. I need the first special attribute called manager.collection_name which may be found in base classes provided in metaclass arguments. (What’s meta class? See this StackOverflow for info). Anyway here is the code.
def __new__(cls, clsname, bases, dct):
parent_collection_name = next((x.manager.collection_name for x in bases if hasattr(x, 'manager')), None)
# ... do other stuff
clx = super(_FieldSpecAwareMetaClass, cls).__new__(cls, clsname, bases, dct)