When starting to learn oTree, you may face uncertainty about where to
put a particular piece of code. Should it go in
creating_session, etc? Should it be a
Here is a quick guide comparing these various functions.
creating_session: code that is put here will execute
immediately when you click the "Create session" button. Therefore,
when this function executes, all fields will be blank, because the
session has not started yet.
creating_session is where
you can put "setup" code, such as predetermining treatment groups.
This function cannot depend on anything that happens during the
session. For that, you should instead use
before_next_page: This function executes after the player
finishes the page, before proceeding to the next page.
after_all_players_arrive: This function can only be defined on
a WaitPage, not a regular page. It's a good place for doing
computations that depend on other players in the group, like picking
the winner in a multi-player game.
after_all_players_arrive executes just once for the whole
before_next_page executes separately for
vars_for_template: This function executes when a page is
loaded. Be aware that if the user reloads the page, this code will get
re-run. This can be convenient during development, since you can
easily edit your code and reload the page to see the result. But make
sure the code you put here is idempotent; otherwise, it could be
exploited by participants. For example, if you have code that randomly
chooses the participant's payoff, the participant could keep reloading
the page until they see a payoff that they like. It's safer to use
before_next_page, which is guaranteed to only execute
User-defined functions: in oTree apps, you will frequently see
user-defined functions such as
def set_payoffs(group): You can define
player/group/subsession functions with whatever name you want, but
unlike built-in functions, oTree won't execute these functions
automatically. It's up to you to call these functions from a built-in
function such as