YouTube

Got a YouTube account?

New: enable viewer-created translations and captions on your YouTube channel!

English subtitles

← 05-08 Named Tuples

dummy description

Get Embed Code
1 Language

Showing Revision 1 created 05/13/2012 by Amara Bot.

  1. Now here's an alternative.
  2. Instead of just defining a state by just creating a tuple
  3. and then getting at the fields of a state by doing an assignment,
  4. we can use something called a namedtuple that gives a name to the tuple itself
  5. as well as to the individual elements.
  6. We can define a new data type called state and use capitalized letters for data types.
  7. Say state is equal to a namedtuple, and the name of the data type is state,
  8. and the fields of the data type are p, me, you, and pending.
  9. So I can just go ahead and make that assertion.
  10. Namedtuples is in a module.
  11. So, from collections import namedtuple gives me access to it.
  12. Now I can say s = state (1,2,3,4), and I can ask for the components of s by name.
  13. How would I choose between this representation for states
  14. and the normal tuple representation?
  15. Well the namedtuple had a couple of advantages.
  16. It's explicit about the types.
  17. It helps you catch errors.
  18. So if you ask for the p field of something that's not a state
  19. that would give you an error.
  20. Whereas if you just broke up something that was four elements into these components
  21. that would work even if it didn't happen to be a proper state.
  22. There are a few negatives as well.
  23. It's a little bit more verbose, although not so much,
  24. and it may be unfamiliar to some programmers.
  25. It may take them a while to understand what namedtuples mean.
  26. I should say we could also do the same type of thing by defining a class.
  27. That has all the same positives,
  28. and it's certainly familiar to most Python programmers,
  29. but it would be even more verbose.
  30. Here's what hold and roll look like in this new notation.
  31. So, hold--where we're explicitly creating a new state.
  32. We look at the state.p, the state.you, the state.me, and the state.pending and so on,
  33. similarly for roll.
  34. They look fairly similar.
  35. You notice the lines are a little bit longer in terms of we're being more explicit.
  36. So, it takes a little bit more to say that.
  37. I'm sort of up in the air whether this representation is better
  38. than the previous representation with tuples.
  39. I could go either way.