<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Liz Johnson on Medium]]></title>
        <description><![CDATA[Stories by Liz Johnson on Medium]]></description>
        <link>https://medium.com/@lizjohnson_83228?source=rss-dc96332236ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u_tqSa0bQ9r5cYnJGmmlag.jpeg</url>
            <title>Stories by Liz Johnson on Medium</title>
            <link>https://medium.com/@lizjohnson_83228?source=rss-dc96332236ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:37:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lizjohnson_83228/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Difference Between Push and Pull Request Triggers in Github]]></title>
            <link>https://medium.com/@lizjohnson_83228/the-difference-between-push-and-pull-request-triggers-in-github-d7c0f2bc19db?source=rss-dc96332236ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7c0f2bc19db</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Liz Johnson]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 22:55:53 GMT</pubDate>
            <atom:updated>2025-05-13T13:13:35.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wkja88bP65Nx45sJoph9Pw.jpeg" /></figure><p>POV: you join a new project that already has a great CI/CD setup. These people really know what they’re doing. And you must be a fantastic judge of character for choosing to join them.</p><p>You complete a piece of work and open a PR and you notice that there are two Github actions that seem to run tests. The output on the PR looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFIwPFYb1bAQTOC8XrdQeg.png" /></figure><p>That really looks like they are running the same CI process twice… That seems like an unnecessary use of resources and time.</p><p>Even worse, you just opened a PR and somehow the (push) action succeed, and yet the (pull_request) action fails. How can that be possible? Aren’t they testing the same thing? And now this faulty, redundant Github action is preventing you from merging!</p><p>You decide to assume the best of the people who seemed to be doing so much good and you come to find out that pushand pull_requestGithub triggers do, in fact, run your tests and/or attempt to build your application using two different sets of code.</p><h3>What’s the Difference</h3><p>If you look at the <a href="https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows">Github documentation</a> on their various triggers you’ll find this description under the Github SHA column of the pull_request trigger:</p><p>“Last merge commit on the GITHUB_REF branch”</p><p>Ok, cool so what is that? The “Last merge commit” is the result of the merging your changes from the branch that you are working on into the target branch.</p><p>So if you created a branch named my-feature and you are trying to merge that into main the pull_request trigger is running on the result of my-feature being merged into main.</p><p>The push trigger, on the other hand, is running on the code from your branch only.</p><p>Here are a couple pictures to help represent the code that the two triggers run on. Say at commit A you branch off and create commits E, F, and G. While you’re working your teammates push commits B, C, and D to main. You open a pull request, requesting that your code is merged from your branch into main.</p><p>Below is a representation of what thepull_request trigger runs on. It would run on H which is the result of your commits merged with the commits on main.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTVderxkMu97FrrfECJLhw.png" /><figcaption>state of the world that the pull_request flow sees</figcaption></figure><p>Even if main had not changed from when you opened your branch to when you attempt to merge it in the commit that the pull_request workflow will run on will be different than the push workflow. In the case below it will run on the result of G merged into A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*557f9Wysymam2Kr465RAMw.png" /></figure><p>Now, here is a representation of what the push trigger runs on. It would run on G — which is all the commits up to A plus the three commits (E, F, and G) that you made to your branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3HX-_0beWneGYYwKfwBCw.png" /><figcaption>state of the world that the push flow sees</figcaption></figure><p>As you can see, the two workflow triggers run on different versions of the code.</p><h3>Why It’s Important To Have Both</h3><p>Both of these workflows are valuable and I would advocate for having both of them configured for your applications.</p><h4>Why Pull Request?</h4><p>I’m sure you can image why the pull request trigger would be valuable especially if a merge to main causes an automatic deploy to production (or any environment that devs or other users are in regularly).</p><p>Pull request triggered workflows are valuable because knowing that the <em>merge commit </em>doesn’t break the test gives you greater confidence that your branch is safe to merge.</p><p>The amount of confidence it gives you depends on a couple other things. First, I want to note that if you workflow runs tests you can only trust the result as much as you trust your test suite. Let’s assume here that you have a very robust test suite that gives you great confidence when it succeeds.</p><p>There are two scenarios that are worth walking through here.</p><h4>Scenario 1: Nothing new in main branch since your PR was opened</h4><p>When the pull request workflow runs it will validate that all your tests pass on the merge of main at the time the workflow runs and your branch. Let’s say that the Git log looks something like this when your workflow runs and it still looks like this right before you hit the merge button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTVderxkMu97FrrfECJLhw.png" /><figcaption>state of the world that the pull_request flow sees</figcaption></figure><p>If the tests pass when run on commit H and you were to deploy from merges to main you can be certain that the tests passed on the code that will be deployed when you merge your PR.</p><h4>Scenario 2: New commits in main branch since your PR was opened</h4><p>If several things got commited between the time of the workflow running and you actually hitting the “Merge pull request” button then the state of the world before you hit merge pull request now looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fU99NlbU4xjVkN4Jkj8nbA.png" /></figure><p>If you are deploying to production on merges to main then even though your workflow ran on H and succeeded when you hit the merge pull request button what will actually get deployed is merge commit K which your workflow never ran on.</p><p>In order to ensure that the tests run on the merge commit created by your branch merged into the <em>latest</em> version of main you can choose to require up to date branches in Github before merging (<a href="https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/managing-a-branch-protection-rule">instructions here</a>). This will prevent your PRs from merging unless all checks pass on the latest version of main merged with your branch.</p><p>Having the pull_request workflow is incredibly important if you want to have confidence in the state of your code before PRs merge to main and potentially deploy to production. Next, I will explain the value that the push workflow has when used with a pull_request workflow.</p><h4>Why Push?</h4><p>Imagine if you created a branch, tested it locally, and all the tests pass. Now you open a PR and the pull_request test run is failing. Many developers who don’t know what that is really testing against would become very confused. Having the push trigger allows additional insights into why the pull_request workflow might be failing. The key is that the branch being merged into introduces code that doesn’t play nicely with yours. While your branch may be fine in and of itself the failure of one while the other is passing indicates you should update your branch with the latest main and rerun tests locally in order to allow the two pieces of code to work together. The two workflows together provider faster feedback and more insights of what might be happening.</p><p>This configuration ensures that branches aren’t merged into main unless the merge commit passes the tests, and it allows developers quick feedback on whether or not it was changes on their own branch failing or some sort of issue in the future merge to main that caused failures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7c0f2bc19db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use and Test React Custom Hooks]]></title>
            <link>https://medium.com/@lizjohnson_83228/how-to-use-and-test-react-custom-hooks-26de35cd08d4?source=rss-dc96332236ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/26de35cd08d4</guid>
            <category><![CDATA[custom-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Liz Johnson]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 22:55:38 GMT</pubDate>
            <atom:updated>2024-02-21T15:21:44.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbKHx6NQlEr4x0S-wYMLxA.jpeg" /></figure><p>React comes with several built in hooks, but sometimes you want to create your own in order to build out logic in one place that can be reused across multiple components. (<a href="https://react.dev/learn/reusing-logic-with-custom-hooks">React Docs</a>)</p><h4>Creating the Custom Hook</h4><p>One reason you might consider a custom hook is when you have an application and several different pages that all need to fetch the same list of records. Say you have several pages of your application that need a list of all the participant records. Your backend provides a /participants endpoint that will return all the participants for you. Once you retrieve the participants then you want to parse the response into a list of Participant typed records.</p><p>On each page that you need the participant list you would need to populate an array of participant records that look like this:</p><p>const participants: Participant[]</p><p>And the participant type would be defined like this:</p><pre>interface Participant {<br>    id: number;<br>    first_name: string;<br>    last_name: string;<br>    birthdate?: string;<br>}</pre><p>You could do two things whenever you need the participants. On each page that you need the participants list you could add a useEffect hook that, on page load, queries the backend for all the participants. That would look something like this:</p><pre>const Participants: NextPage = () =&gt; {<br>    const [apiData, setApiData] = useState([]);<br>    const [isLoading, setIsLoading] = useState(false);<br>    const httpClient = useHttpClient();<br><br>    const columns = getParticipantColumns()<br><br>    useEffect(() =&gt; {<br>      setIsLoading(true)<br>      httpClient.get(&#39;/participants&#39;).then(response =&gt; {<br>        setApiData(response.data)<br>        setIsLoading(false)<br>        return { participants: apiData, isLoading: isLoading }<br>      })<br>      .catch(error =&gt; {<br>        console.log(error)<br>      })<br>    }, []);<br><br>    return (<br>        &lt;div&gt;<br>                &lt;Box sx={{textAlign:&#39;left&#39;, height: 400, width: &#39;100%&#39;}}&gt;<br>                    &lt;Typography variant={&#39;h6&#39;}&gt; Participants &lt;/Typography&gt;<br>                   &lt;div style={{ height: 250, width: &#39;100%&#39; }}&gt;<br>                    &lt;DataGrid<br>                        rows={participants}<br>                        columns={columns}<br>                        initialState={{<br>                            pagination: {<br>                                paginationModel: {<br>                                    pageSize: 5,<br>                                },<br>                            },<br>                        }}<br>                        pageSizeOptions={[5]}<br>                        checkboxSelection<br>                        disableRowSelectionOnClick<br>                    /&gt;<br>                   &lt;/div&gt;<br>                &lt;/Box&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><p>In order to have multiple pages querying for participants you would need to copy and paste that useEffect on each page that needed the participant list. Instead, we can create a custom hook that will hold all the logic for retrieving users it will look something like this:</p><pre>import {useHttpClient} from &quot;./useHttpClient&quot;;<br>import {useEffect, useState} from &quot;react&quot;;<br><br>interface Participant {<br>    id: number;<br>    first_name: string;<br>    last_name: string;<br>    birthdate?: string;<br>}<br><br>function useParticipants(): { participants: Participant[], isLoading: boolean } {<br>    const [apiData, setApiData] = useState([]);<br>    const [isLoading, setIsLoading] = useState(false);<br>    const httpClient = useHttpClient();<br><br>    useEffect(() =&gt; {<br>      setIsLoading(true)<br>      httpClient.get(&#39;/participants&#39;).then(response =&gt; {<br>        setApiData(response.data)<br>        setIsLoading(false)<br>        return { participants: apiData, isLoading: isLoading }<br>      })<br>      .catch(error =&gt; {<br>        console.log(error)<br>      })<br>    }, []);<br><br>    return { participants: apiData, isLoading: isLoading }<br>}<br><br>export default useParticipants;</pre><p>Now our participants page can be refactored to look something like this:</p><pre>const Participants: NextPage = () =&gt; {<br>    const { participants, isLoading } = useParticipants();<br><br>    const columns = getParticipantColumns()<br><br>    return (<br>        &lt;div&gt;<br>                &lt;Box sx={{textAlign:&#39;left&#39;, height: 400, width: &#39;100%&#39;}}&gt;<br>                    &lt;Typography variant={&#39;h6&#39;}&gt; Participants &lt;/Typography&gt;<br>                   &lt;div style={{ height: 250, width: &#39;100%&#39; }}&gt;<br>                    &lt;DataGrid<br>                        rows={participants}<br>                        columns={columns}<br>                        initialState={{<br>                            pagination: {<br>                                paginationModel: {<br>                                    pageSize: 5,<br>                                },<br>                            },<br>                        }}<br>                        pageSizeOptions={[5]}<br>                        checkboxSelection<br>                        disableRowSelectionOnClick<br>                    /&gt;<br>                   &lt;/div&gt;<br>                &lt;/Box&gt;<br>        &lt;/div&gt;<br>    );<br>}<br><br>export default ParticipantsList;</pre><p>All we really did here is move that useEffect into a custom named hook but it cleans up that page a lot. Not only that but if you have any components that would require a list of participants you can get the list by using useParticipants() hook. They could be drop downs that exist on separate pages that require a list of all participants.</p><h4>Testing the Custom Hook</h4><p>First, I want to explain why you would test a custom hook. In general, I see unit tests as having two major benefits:</p><ol><li>Unit tests provider faster feedback as you work towards a working solution</li><li>Unit tests will prevent regressions in your applications behavior.</li></ol><p>So why would you test your custom hooks specifically? In these examples I am focused on custom hooks used for data retrieval. Many times there is some layer of serialization logic involved in hooks that retrieve data. Your component that uses the data retrieved by this hook will count on the data being structured a certain way and it may rely on certain data elements being present. A unit test at this level will help you get that serialization logic in place in a way you know is correct and it will prevent future changes to the code from doing anything that would modify the result of the hook in some breaking way.</p><p>A couple options exist for testing custom hooks. One option is to use React Testing Library’s renderHook function. The documentation for that can be found <a href="https://react-hooks-testing-library.com/reference/api#renderhook">here</a>.</p><p>This method will render a test component that will call the provided callback. So in our case we would want a callback that calls our useParticipants() hook. We can use renderHook with our custom hook like this:</p><pre>renderHook(() =&gt; useParticipants())</pre><p>To use the renderHookfunction we could write a test that looks something like this:</p><pre>import {waitFor, render, screen, act} from &quot;@testing-library/react&quot;;<br>import {AxiosInstance} from &quot;axios&quot;;<br>import useParticipants from &quot;./useParticipants&quot;;<br>import React from &quot;react&quot;;<br>import {useHttpClient} from &quot;./useHttpClient&quot;;<br>import { renderHook } from &#39;@testing-library/react&#39;<br><br>jest.mock(&quot;./useHttpClient&quot;)<br><br>const mockedUseHttpClient = jest.mocked(useHttpClient, true)<br>describe(&#39;useParticipants&#39;, () =&gt; {<br>  const mockHttpClient = {<br>    get: jest.fn(),<br>    post: jest.fn()<br>  }<br>  beforeEach(async () =&gt; {<br>    const expectedParticipantsResponse = {<br>      data: [<br>        {<br>          &quot;id&quot;:1,<br>          &quot;first_name&quot;:&quot;clayton&quot;,<br>          &quot;last_name&quot;:&quot;johnson&quot;,<br>          &quot;birthdate&quot;:&quot;2016-04-16&quot;,<br>        }<br>      ]<br>    }<br>    mockedUseHttpClient.mockReturnValue(((mockHttpClient as unknown) as AxiosInstance))<br>    mockHttpClient.get.mockReturnValue(Promise.resolve(expectedParticipantsResponse))<br>    mockHttpClient.post.mockReturnValue(expectedParticipantsResponse)<br>  });<br><br>  it(&quot;automatically fetches the given URL when called&quot;, async () =&gt; {<br>      const { result } = renderHook(() =&gt; useParticipants())<br><br>      await waitFor(() =&gt; {<br>        expect(result.current.participants).toEqual([{<br>          &quot;id&quot;:1,<br>          &quot;first_name&quot;:&quot;clayton&quot;,<br>          &quot;last_name&quot;:&quot;johnson&quot;,<br>          &quot;birthdate&quot;:&quot;2016-04-16&quot;<br>        }])<br>        expect(mockHttpClient.get).toHaveBeenCalledWith(&#39;/participants&#39;)<br>      })<br>  })<br>});</pre><p>You’ll notice that in our test we need to waitFor the result because our hook is taking an async action to retrieve data.</p><p>The renderHook function will return a result object that looks something like this:</p><pre>{<br>  all: Array&lt;any&gt;<br>  current: any,<br>  error: Error<br>}</pre><p>In our test above after we wait for the promise to resolve we get a result that looks something like this:</p><pre>{<br>      participants: [<br>        {<br>          id: 1,<br>          first_name: &#39;clayton&#39;,<br>          last_name: &#39;johnson&#39;,<br>          birthdate: &#39;2016-04-16&#39;<br>        }<br>      ],<br>      isLoading: false<br>}</pre><p>We can make assertions on that result based on things we know we will need in our component.</p><p>The other option you have is to build your own test component and use the custom hook inside that component.</p><pre>import {waitFor, render, screen, act} from &quot;@testing-library/react&quot;;<br>import {AxiosInstance} from &quot;axios&quot;;<br>import useParticipants from &quot;./useParticipants&quot;;<br>import React from &quot;react&quot;;<br>import {useHttpClient} from &quot;./useHttpClient&quot;;<br><br>jest.mock(&quot;./useHttpClient&quot;)<br><br>const mockedUseHttpClient = jest.mocked(useHttpClient, true)<br>const TestParticipantsComponent = () =&gt; {<br>  const {participants, isLoading} = useParticipants()<br>  return (<br>    &lt;&gt;{<br>        isLoading ?<br>          &lt;&gt;&lt;/&gt; :<br>          &lt;div&gt;<br>            {<br>              participants.map((p) =&gt; {<br>                return (<br>                  &lt;&gt;<br>                    &lt;li&gt;First Name: {p.first_name}&lt;/li&gt;<br>                    &lt;li&gt;Last Name: {p.last_name}&lt;/li&gt;<br>                    &lt;li&gt;ID: {p.id}&lt;/li&gt;<br>                  &lt;/&gt;<br>              )<br>              })<br>            }<br>          &lt;/div&gt;<br>      }<br>    &lt;/&gt;<br>  )<br>}<br><br>describe(&#39;useParticipants&#39;, () =&gt; {<br>  const mockHttpClient = {<br>    get: jest.fn(),<br>    post: jest.fn()<br>  }<br>  beforeEach(async () =&gt; {<br>    const expectedParticipantsResponse = {<br>      data: [<br>        {<br>          &quot;id&quot;:1,<br>          &quot;first_name&quot;:&quot;clayton&quot;,<br>          &quot;last_name&quot;:&quot;johnson&quot;,<br>          &quot;birthdate&quot;:&quot;2000-04-16&quot;,<br>        }<br>      ]<br>    }<br>    mockedUseHttpClient.mockReturnValue(((mockHttpClient as unknown) as AxiosInstance))<br>    mockHttpClient.get.mockReturnValue(Promise.resolve(expectedParticipantsResponse))<br>    mockHttpClient.post.mockReturnValue(expectedParticipantsResponse)<br>  });<br><br>  it(&#39;should return renderable participant data&#39;, async () =&gt; {<br>    act(() =&gt; {<br>      render (<br>        &lt;TestParticipantsComponent/&gt;<br>      )<br>    })<br><br>    expect(mockHttpClient.get.mock.calls[0][0]).toEqual(`/participants`)<br>    await waitFor(() =&gt; {<br>      expect(mockHttpClient.get).toHaveBeenCalledWith(&#39;/participants&#39;)<br>      expect(screen.getByText(/clayton/)).not.toBeNull()<br>      expect(screen.getByText(/1/)).not.toBeNull()<br>    })<br>  });<br>});</pre><p>This test has the benefit of ease of readability. We use the custom hook in a, usually more simplified, way that we expect it to be used in our app. Ultimately, we are testing the same thing with both options. By building and using our own test component in our test we also have the benefit of more simply modeling our we might expect the data returned from the custom hook to be used. Although, with the second implementation because we build a test component we are redoing something that renderHook component does for us already.</p><p>I consider which option you choose between the two a matter of preference. Maybe it depends on the level of developers on your team an how comfortable they would feel with something like renderHook in their tests. Maybe something more verbose would be better!</p><p>In either case there is value in implementing custom hooks to clean up your components and avoid duplication. And there is value in test the hooks in a unit test to ensure their implementation is what is desired, develop quickly and iteratively, and prevent regressions in their behavior.</p><p>These examples can be found in Github <a href="https://github.com/lizzypy/base-app-liz">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26de35cd08d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Data Classes and Callable Classes]]></title>
            <link>https://medium.com/@lizjohnson_83228/python-data-classes-and-callable-classes-ac35511daed7?source=rss-dc96332236ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac35511daed7</guid>
            <category><![CDATA[callable]]></category>
            <category><![CDATA[python-dataclass]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Liz Johnson]]></dc:creator>
            <pubDate>Fri, 09 Sep 2022 22:03:03 GMT</pubDate>
            <atom:updated>2024-02-21T15:21:36.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8C2HMz6tk_-79N4Fzk8kbw.jpeg" /></figure><p>The python data class annotation was introduced to me a few months ago. It has become a go-to pattern for me for several reasons that I will share here. I’ve also been combining it with making classes callable. That could sound like I’m combining two things that ought not be combined; however, I think it’s a useful pattern that has led to modular and well-tested code.</p><h4>Data Classes</h4><p>First, let’s start with the data class annotation. Data classes were originally described as a part of <a href="https://peps.python.org/pep-0557/">pep-557</a>. I encourage you to read through that link to learn more about them as well, but I will give a few highlights here to explain what they are.</p><p>By default, classes annotated with @dataclass get several methods for free. This leads to some really clean-looking classes. Some big things that you get for free with data classes are basic implementations of __init__, __eq__, __repr__, and others! This means that the Activity class below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88d573644fe9b26201b3d8b0422eed74/href">https://medium.com/media/88d573644fe9b26201b3d8b0422eed74/href</a></iframe><p>can be turned into a data class that will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1b442360bac2c69846cbc1e45aa91ac/href">https://medium.com/media/f1b442360bac2c69846cbc1e45aa91ac/href</a></iframe><p>and that’s it! That’s all you need and you get the rest! Now, it’s important to know what you are getting and how it is implemented (which is why <a href="https://peps.python.org/pep-0557/">pep-557</a> is worth a look if this seems as great to you as it does to me) but if you just want some basic methods for instance comparisons this is pretty handy.</p><p>Type annotations are also required on data classes and every property is required by the constructor unless you give it a default value. I use type hints as often as I can with python and it has saved me a decent amount of trouble. So forcing the typing of properties feels like a win.</p><p>If you’d prefer to define any of these methods yourself you can override the default functionality that the data class provides by simply implementing the method in the class. You can also override the defaults of the annotation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b877fa3fca08c0b93f00366329de160e/href">https://medium.com/media/b877fa3fca08c0b93f00366329de160e/href</a></iframe><p>It’s good to know that you can change the default behavior provided by the annotation. The python documentation on data classes explains each of these properties in greater detail <a href="https://docs.python.org/3/library/dataclasses.html">here</a>.</p><p>So far, I’ve primarily used data classes in the most basic way. I want my properties required, typed, and I don’t want to have to write a standard __init__ and __eq__ if I don’t have to. Next, I will explain how I have turned these basic classes into callable objects and why that has increased the modularity and readability of my code.</p><h4>Callable Classes</h4><p>So now I’ll move on to classes as callables. To start I’ll explain how you turn a class into a callable and how that looks when it’s used.</p><p>Turning a class into a callable in python is very simple. You just need to implement the __call__ method in the class. I’ve been using this pattern with classes that are supposed to do something. It doesn’t make sense to me to call something that isn’t performing some sort of action. So as an example here let’s have a class that returns the capacity of an activity based on the grade level of the participants and the teachers available. Let’s assume that this class will have a function as a dependency that will make an external call and return a dictionary of ratios_by_grade that looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ca7261817472e80367a17473d144d07/href">https://medium.com/media/2ca7261817472e80367a17473d144d07/href</a></iframe><p>Then we can create a determine capacity class that looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edb1a5a97b0b0c727710bb2aa713c218/href">https://medium.com/media/edb1a5a97b0b0c727710bb2aa713c218/href</a></iframe><p>If our code wants to use this class to calculate the max capacity of an activity it can do so like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0a93178550877631ddd59ff7eecdab5/href">https://medium.com/media/c0a93178550877631ddd59ff7eecdab5/href</a></iframe><p>So why would we create a class to do something like this instead of just having a python module that looks like this?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/291a75d9b8601c56369e1a750f398933/href">https://medium.com/media/291a75d9b8601c56369e1a750f398933/href</a></iframe><p>The reason that seems most important to me is that the class option has the dependencies injected in order to allow for easier testing. In order to unit test the second option you would need to patch the dependency. While this is definitely doable I’ve found the patch annotation to be confusing and not the easiest to use.</p><h4>Putting them Together</h4><p>So why combine data classes with callable classes? The main benefit is the readability and ease of implementation. In the example above, the dependency is required. By creating it as a data class we can get the constructor for free and the focus of the class implementation is it’s call method. We probably don’t benefit from having an __eq__ and __repr__ implemented for us with these classes. But forced typing on properties and simplified code still feels like a good enough reason to use what can be provided for us with the data class annotation.</p><p>This pattern was introduced to me by David Borenstein who taught me most of what I know about python and data analysis and sparked my interest in machine learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac35511daed7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Python Class Methods to Enable Dependency Injection]]></title>
            <link>https://medium.com/@lizjohnson_83228/using-python-class-methods-to-enable-dependency-injection-b7889a95eab3?source=rss-dc96332236ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7889a95eab3</guid>
            <category><![CDATA[class-method]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Liz Johnson]]></dc:creator>
            <pubDate>Fri, 09 Sep 2022 21:48:28 GMT</pubDate>
            <atom:updated>2024-02-21T15:21:25.284Z</atom:updated>
            <content:encoded><![CDATA[<p>Dependency injection is a useful pattern for many reasons, but one of the biggest reasons I tend to use it is that it easily allows you to mock out dependencies for testing purposes. But when an object requires multiple levels of dependencies to be built the construction of that object can look messy. I’ve found Python class methods can help clean up the construction of that object.</p><p>I’ve spent most of my time in Java, a bit in Typescript and most recently have spent a decent amount of time writing python. While patterns of testing can remain essentially the same between different languages the tools for testing change a bit from language to language.</p><p>If you’re writing a true unit test you’ll want to mock out dependencies so that you are only testing the logic in the class/module under test. The first thing I found to do this in python was patching. I used the annotations provided by the “unittest” library to patch my dependencies like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1bc1af2df52edd4c15c36780920c128/href">https://medium.com/media/d1bc1af2df52edd4c15c36780920c128/href</a></iframe><p>This caused me a lot of pain because I skipped the “read the instructions” step that explains to mock the dependency “where it’s used” and not “where it came from” (s<a href="https://docs.python.org/3/library/unittest.mock.html">ee “Where to Patch”</a>). Knowing that helped. But then I was introduced to a new pattern that allowed me to avoid the @patch annotation almost entirely.</p><p>I’ll explain it here, because I really think it’s just the coolest. Here I’ll show how we build our classes so that they are clean and easily tested. Another thing you’ll see here is the pattern of making classes callable. This pattern feels like it goes well with dependency injection. You can give the class everything it needs, and then invoke it to let it do its thing.</p><p>I grew up in a family of four kids and I’ll never forget the coordination that went into soccer picture day. Four kids, four soccer games, and more activities beyond that - usually all in one Saturday.</p><p>So let’s say that I need a function that can assign children’s activities to a designated caretaker based on care-taker availability. This magical function just needs to do three things:</p><ol><li>Collect activities</li><li>Collect care-taker openings</li><li>Assign activities to a care-taker</li></ol><p>We would like a test that can mock out the dependencies for this function (collect_activities, collect_openings, and assign_activity). That means our test would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33114873bfb9e3df0d02a272364bc53f/href">https://medium.com/media/33114873bfb9e3df0d02a272364bc53f/href</a></iframe><p>If we want a class that can assign activities for us and gets our test to pass we could build something that looks like the class below. Notice that we inject all our dependencies so that the mocking we do above is easy (and our @patch annotation doesn’t have to come into play at all):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a84cfb3d95134e7138669885e377737/href">https://medium.com/media/1a84cfb3d95134e7138669885e377737/href</a></iframe><p>That’s pretty basic dependency injection. My favorite part is coming next though. Let’s say we want this to be called from behind an endpoint, /assign. Here is an example of what the endpoint would look like using flask as our application framework. That endpoint could look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac3ae51253584ad2be08601711a2de09/href">https://medium.com/media/ac3ae51253584ad2be08601711a2de09/href</a></iframe><p>That looks okay because our class doesn’t have that many dependencies, nor are the dependencies it has very complicated. But let’s say that assign_acitivity isn’t a simple function, but rather a class with its own dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3c5800c3b694dd8d97ab42f30774799/href">https://medium.com/media/c3c5800c3b694dd8d97ab42f30774799/href</a></iframe><p>That’s becoming a lot to look at. But we can clean that up and make it look really nice! We can write a class method in the MakeAssignments class that allows the class to know how to build itself. For our MakeAssignments class that would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73903df4343f9964f2e3c5930eca5d78/href">https://medium.com/media/73903df4343f9964f2e3c5930eca5d78/href</a></iframe><p>Now in our assignment() method we can have something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84b1544f37c01e48cca0def7e03e1caf/href">https://medium.com/media/84b1544f37c01e48cca0def7e03e1caf/href</a></iframe><p>Nice! So much cleaner. And our test doesn’t change! We can instantiate the class with the mocks via the constructor for the test and we can use the build method in the rest of our code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7889a95eab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>