cs111
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: Labs-F21, 2021 title: Lab 10 --- # Lab 10: Understanding and Testing Mutation In this lab, we will continue with two ideas that we introduced in lecture: understanding how data mutation works and testing functions that mutate data. ## An Example of Sharing Data: Collaborative Editing When a program is maintaining data over time, sometimes we want that data to be shared across different parts of the program and sometimes we do not. Decisions about what should or should not be shared affect how we set up our data and write programs. ### Dataclasses, Examples, and Memory Diagrams Consider a tool (like Google Docs) that allows people to create documents and share them with other people. Here's a basic dataclass for Documents. ``` from datetime import datetime from dataclasses import dataclass @dataclass class Document: title: str last_edited: datetime contents: str hwk1 = Document("Homework 1", datetime(2021,11,15,13,24,36,10), "Write a program") # the parts of datetime are year, month, date, hours, mins, ... ``` Another basic dataclass captures people who are allowed to edit documents: ``` @dataclass class Editor: name: str docs: list annie = Editor("annie", [hwk1]) ``` Imagine that the CS111 homeworks team is preparing assignments that are in different stages of readiness. Some documents are ready for sharing with others, but some stay private until the creators are ready to share them. **Task:** Copy the above code fragments to a Python file. Add variables and definitions to set up the following set of editors and documents with their corresponding sharing settings: - Michelle as an editor with no documents - Ricky as an editor who is also working on homework 1 - Kenny as an editor who is working on homework 2 (which is not yet shared with anyone) **Task:** Draw the memory-layout diagram for the current collection of Editors and Documents. --- :::spoiler **What's a memory-layout diagram???** :::info Consider the following program: ``` @dataclass class Planet: name: str size: num @dataclass class GalacticOverlord: name: str species: str rulerOf: Planet earth = Planet("Earth", 10) mars = Planet("Mars", 8) paul = GalacticOverlord("Paul", "Martian", mars) crowl = GalacticOverlord("Crowley", "Ferret", earth) ``` We could draw our memory-layout diagram like this, where each box represents our data in memory. Each box resides in some location in memory (written as locXXXX). When a variable or field references another piece of data in memory, we use the location to identify the piece of data. If we want, we can highlight the references between variables/fields and data by also drawing arrows that connect a reference to a location with the actual piece of data. The arrows, however, mask a key piece of what is happening: that data live in spots in memory with unique numeric identifiers. ![](https://i.imgur.com/QZ3kFrs.png) **It is critically important that names from the directory do not appear in the heap area/inside the data**. Using the names suggests that later updates to the variable values (like ```earth = ...```) would affect the data in the heap, but this is NOT how languages work. ::: ___ ### *CHECKPOINT:* Call over a TA once you reach this point. Note that the TA can ask either partner to answer, so please make sure both partners understand the diagrams. ___ Annie has an inspiration for new ideas for homework 2. She doesn't want to disrupt Kenny's progress, but she does want to try re-working content to see if her ideas make sense. **Task:** Extend your memory-layout diagram to show Annie being the sole editor of a copy of Kenny's current homework 2 draft. Upload a picture of your memory-layout diagram from lab so far to this [Google Form](https://docs.google.com/forms/d/e/1FAIpQLSfZeq8GOENgkMnOTiNHFjuNfxmXXMUbPLxRt6T7INnjjEz78w/viewform?usp=sf_link). **Task:** Add some code to your file that would create the same memory contents as what you just drew to give Annie a copy of homework 2. Annie and Ricky have been working on homework 1, but their idea isn't working out. It's such a mess that they have decided to just throw away their old attempt and start over. **Task:** Here are two ways to "start over" on homework 1. What effect will each have on the memory diagram? After taking each approach (separately), what contents will Python produce if we ask to see annie's version of hwk1? ``` # Approach #1 hwk1 = Document("Homework 1", datetime.now, "This is much better") #Approach #2 hwk1.last_edited = datetime.now() hwk1.contents = "" ``` One of the most subtle concepts to internalize when starting to work with updating data is the difference between updating **variables** and updating **contents of data structures**. The previous task highlights the differences. **Task:** To help you internalize these details, please talk through the following questions with your partner. 1. If we update what `hwk1` refers to using approach 1, which editors will see the changes? - Anyone that already had access to the old hwk1 - Anyone that gets access to hwk1 in the future - Both past and future editors of hwk1 2. If we update what `hwk1` refers to using approach 1, will there be any way to access the original `hwk1` contents? 3. If we update the contents of hwk1 using approach 2, which editors will see the changes? - Anyone that already had access to the old hwk1 - Anyone that gets access to hwk1 in the future - Both past and future editors of hwk1 4. If we update what `hwk1` refers to using approach 2, will there be any way to access the original `hwk1` contents? ### Functions for Key Document Tasks Creating, sharing, editing, and copying documents happen so often that it would make sense to have functions corresponding to those tasks. **Task:** Write a function `create` that takes an `Editor` and a document title. The function creates a new document, stores it in the editor's list of docs, then returns the new document. **Task:** Write a function `edit` that takes a Document and a string (for the new content) and replaces the document contents with the new text. **Task:** Write a function `share` that takes a `Document` and an `Editor` and adds the document to the editor's list of docs. **Task:** Write a function `copy` that takes a document and returns a copy of the document. The copy has the same title and contents as the original, but the `last_edited` component is the current date and time (use `datetime.now()` to get this). **Task:** Look back at your four functions: which ones return something and which ones don't? Focus on the ones that don't return anything. Do they "accomplish" anything? Can you articulate what a function that doesn't return anything has to "do" in order to be of use? Write down your answer. (*hint: think about memory diagrams*) ___ ### *CHECKPOINT:* Call over a TA once you reach this point. ___ ### Testing Now, we have to figure out whether the functions you've written provide the sharing conditions that we had in mind. In particular, think about the `edit`, `share`, and `copy` functions. Your goal is to fill in this template of a testing function: ```=python def test_docs(): "SETUP" # your scenario setup goes here "PERFORM MODIFICATIONS" # calls to your functions go here "CHECK EFFECTS" # assertions go here ``` **Task:** Identify an initial scenario of editors and documents against which you will run your tests. Create the corresponding data in the "SETUP" area of `test_docs`. **Task:** Write down (in prose) a list of effects that these operations **should** have. Put these in a multi-line string comment above your `test_docs` function in your file: ```=python """ Expected effects: - If we create a doc titled t for an editor, the editor will have a document with title t in their docs list - YOU ADD MORE ITEMS HERE """ ``` **Task:** Write down a list of effects that these operations should **not** have. For example, "if one document is edited, then the contents of another document should not change". Add these in a separate comment like the one above in your file. **Task:** Make a collection of calls to the `edit`, `share`, and `copy` functions in the "PERFORM MODIFICATIONS" section. These calls should be sufficient to perform the checks that you outlined in your lists of effects. **Task:** Turn your expected and unexpected effects into pytest assertions, putting those in the "CHECK EFFECTS" section of the testing function. **Task:** We are curious to see which effects groups are and aren't identifying. Please visit this [Google Form](https://forms.gle/gxLRm3o6rM4HnFRk6), and copy/paste your prose lists of expected effects. ___ ### *CHECKPOINT:* Call over a TA once you reach this point. ___ ### Reviewing Global and Return In a large course staff like we have for 111, having a separate variable for each TA/Prof makes our code a bit hard to manage. It therefore makes sense to make a list to hold all of the editors on our documents, as follows: ```=python all_staff = [Editor("kathi", []), Editor("milda", []), Editor("erick", []) ...] ``` To help us keep track of all the documents we are working on, we want to make two additions to our current code: we want to be able to ask which staff have access to a particular document, and we want to maintain a count of how many documents we have. Let's start with the latter. We'll set up a new variable to maintain the count of documents that we have created. We'll also modify our `copy` function to update this count. **Task:** The code below shows `copy` modified to update `num_docs`. The code has two commented-out `global` lines. Which of the two are needed here, and why (or why not)? ```=python num_docs = 0 def copy(doc) -> Document: # global num_docs # global doc num_docs = num_docs + 1 return Document(doc.title, datetime.now(), doc.contents) ``` **Task:** The following code computes a list of all staff who can access a specific document. The code has two commented-out `global` lines. Which of the two are needed here, and why (or why not)? ```=python def who_has(doc) -> list: "Produce list of editors with access to given doc" # global can_access # global all_staff can_access = [] for editor in all_staff: if doc in editor.docs: can_access.append(editor) # return alternative 1 # return alternative 2 return can_access ``` **Task:** The `who_has` function indents the `return` under the `for` loop. We could also have indented the `return` at the corresponding comments. Describe in prose what each return position would result in compared to the original `return` position. If you are finished with time to spare, feel free to take time to get ahead on the homework. ___ ### *CHECKPOINT:* Call over a TA once you reach this point. ___

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully