I have a list of posts. I need to generate it each one by one. For generation of each post, I need to know about other posts. However, I want to make the current post marked.
def generate(posts):
print(posts) #faking generation
def marked_active_post(orig_posts, active_index):
posts_view = orig_posts.copy()
active_post = orig_posts[active_index]
active_post = orig_posts[active_index].copy()
active_post['active?'] = True
posts_view[active_index] = active_post
return posts_view
posts = [{'foo':'bar'}, {'aaa':'bbb'}]
for i in range(0, len(posts)):
generate(marked_active_post(posts, i))
How can I do better?
2 Answers 2
It's too bad your template engine doesn't support conditions. What about this?
def marked_active_post(orig_posts, active_index):
posts_view = orig_posts.deepcopy()
posts_view[active_index]['active?'] = True
return posts_view
That means n+1 copies instead of 2, but no need to optimize it until it proves to be slow.
-
\$\begingroup\$ I don't like this code either. But can not come up with better approach. \$\endgroup\$Stan Kurilin– Stan Kurilin2014年09月23日 14:07:15 +00:00Commented Sep 23, 2014 at 14:07
It's a very simple point which I'm sure you already know, but I wanted to say it anyway just in case.
You should wrap the main execution like the following:
if __name__ == '__main__':
posts = [{'foo':'bar'}, {'aaa':'bbb'}]
for i in range(0, len(posts)):
generate(marked_active_post(posts, i))
This allows you to import your script into other scripts without anything actually running.
-
\$\begingroup\$ Thank you for mention it. It could be useful for readers. \$\endgroup\$Stan Kurilin– Stan Kurilin2014年09月25日 17:29:18 +00:00Commented Sep 25, 2014 at 17:29
i
tells you which post is current. So why not use that? \$\endgroup\$