still.Learning
still.Learning

Reputation: 1245

Get a list of object properties from list of objects in python

I will give you my specific example but this is a general python question.

I have a list of apscheduler job objects Link I am trying to figure out what is the most efficient way to get a list of the apscheduler job property, 'kwargs' from my list of apscheduler jobs.

I know I can just iterate through the whole list and make a new list of kwargs, but I was wondering if there is a more efficient/ cleaner way to do this in python, since I am new to it. Thanks!

from apscheduler.scheduler import Scheduler

schedule = Scheduler()
jobs = schedule.get_jobs() #jobs is a list of apscheduler jobs
jobs_kwargs = ???

Upvotes: 0

Views: 347

Answers (3)

still.Learning
still.Learning

Reputation: 1245

Figured it out with a little help from a coworker. This can be done by using map:

from apscheduler.scheduler import Scheduler

schedule = Scheduler()
jobs = schedule.get_jobs() #jobs is a list of apscheduler jobs
jobs_kwargs = map(lambda k: k.kwargs, jobs)

This is supposedly more efficient as it parallel processes the task(I still have to look into it for more information). Thanks for the suggestions though!

Upvotes: 1

DevLounge
DevLounge

Reputation: 8437

I agree with John on this.

Maybe a suggestion:

If your jobs objects are all of the Schedule class type, dynamically append to the class attribute (not self but cls) i.e. kwargs each job object kwargs whenever one gets instantiated, so that at anytime, you could read from that class attribute. via i.e. a classmethod called i.e. schedule.get_gwargs(cls).

But I am not sure this brings anything better than a simple list comprehension.

Upvotes: 0

John Vinyard
John Vinyard

Reputation: 13485

Well, you pretty much said it:

jobs = schedule.get_jobs()
jobs_kwargs = [j.kwargs for j in jobs]

As far as I know, there's really no "cleaner" way than that.

Upvotes: 1

Related Questions