2
\$\begingroup\$

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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 23, 2014 at 13:21
\$\endgroup\$
3
  • \$\begingroup\$ Created as a more detailed question from codereview.stackexchange.com/questions/63174/… \$\endgroup\$ Commented Sep 23, 2014 at 13:23
  • \$\begingroup\$ The loop variable i tells you which post is current. So why not use that? \$\endgroup\$ Commented Sep 23, 2014 at 14:09
  • \$\begingroup\$ @Gareth - I can not do any logic in my template engine (pystache). \$\endgroup\$ Commented Sep 23, 2014 at 14:12

2 Answers 2

2
\$\begingroup\$

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.

answered Sep 23, 2014 at 14:01
\$\endgroup\$
1
  • \$\begingroup\$ I don't like this code either. But can not come up with better approach. \$\endgroup\$ Commented Sep 23, 2014 at 14:07
1
\$\begingroup\$

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.

answered Sep 23, 2014 at 22:19
\$\endgroup\$
1
  • \$\begingroup\$ Thank you for mention it. It could be useful for readers. \$\endgroup\$ Commented Sep 25, 2014 at 17:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.