objects

I made functions that make dictionaries (test_factory_w_keyword_arguments) and strings (test_factory_person_says_hello) in how to make a person.

I can also use an object for a person, because it is a group of attributes (variables) and methods (functions) that belong together.


preview

I have these tests by the end of the chapter

questions about objects


requirements

how to make a person


open the project

  • I change directory to the person folder

    terminal
    cd person
    

    the terminal shows I am in the person folder

    .../pumping_python/person
    
  • I use pytest-watcher to run the tests

    terminal
    uv run pytest-watcher . --now --patterns "**/*.py"
    

    the terminal is my friend, and shows

    terminal
    rootdir: .../pumping_python/person
    configfile: pyproject.toml
    collected 3 items
    
    tests/test_person.py ...                              [100%]
    
    ==================== 3 passed in X.YZs =====================
    
  • I hold ctrl on the keyboard, then click on tests/test_person.py to open it


test_classy_person_says_hello

I made a person say hello with a function, I can also do the same thing with an object because it is attributes and methods that belong together.


RED: make it fail


I add a new test to test_person.py

 69    def test_factory_person_says_hello(self):
 70        first_name = get_random_name()
 71        last_name = get_random_name()
 72        sex = pick_one('F', 'M')
 73
 74        year_of_birth = get_random_year_of_birth()
 75        age = calculate_age(year_of_birth)
 76
 77        a_random_person = src.person.person(
 78            first_name=first_name,
 79            last_name=last_name,
 80            sex=sex,
 81            year_of_birth=year_of_birth,
 82        )
 83
 84        reality = src.person.say_hello(a_random_person)
 85        my_expectation = (
 86            f'Hello, my name is {first_name} {last_name}'
 87            f' and I am {age}'
 88        )
 89        self.assertEqual(reality, my_expectation)
 90
 91    def test_classy_person_says_hello(self):
 92        joe = src.person.Person(
 93            first_name='joe',
 94            last_name='blow',
 95            year_of_birth=1996,
 96        )
 97
 98        reality = src.person.say_hello(joe)
 99        my_expectation = None
100        self.assertEqual(reality, my_expectation)
101
102
103# Exceptions seen

the terminal is my friend, and shows AttributeError

AttributeError: module 'src.person' has no attribute 'Person'

because there is no definition for Person in src/person/__init__.py in the src folder


GREEN: make it pass


  • I add an object to src/person/__init__.py

  • I add a constructor method to the Person object so it can take arguments, it is used to define how copies of the object are made

    the terminal is my friend, and shows TypeError

    TypeError:
        Person.__init__() got an
        unexpected keyword argument 'first_name'
    
    • because the definition for __init__ does not allow calling it with inputs (the parentheses are empty) and the test sends 'first_name' as input.

    • a constructor method is used to make copies of an object

  • I add the name in parentheses so that the __init__ constructor method can take input

    the terminal is my friend, and shows TypeError

    TypeError:
        Person.__init__() got
        multiple values for argument 'first_name'
    

    because the __init__ constructor method takes the instance it belongs to as the first argument

  • I add self as the first argument the way I do with all the test methods in the book

    • self is Python convention, I can use any name I want

    • the terminal is my friend, and shows TypeError

      TypeError:
          Person.__init__() got
          an unexpected keyword argument 'last_name'.
          Did you mean 'first_name'?
      

      I have seen this before, so far it is the same as making the person function

  • I add last_name to the definition of __init__

    the terminal is my friend, and shows TypeError

    TypeError:
        Person.__init__() got
        an unexpected keyword argument 'year_of_birth'
    

    still the same as making the person function

  • I add year_of_birth to the definition of the __init__ method

    the terminal is my friend, and shows AttributeError

    AttributeError:
        'Person' object has no attribute 'get'
    

    because

  • I change reality in test_classy_person_says_hello to use a method I can add to Person, in test_person.py

    the terminal is my friend, and shows AttributeError

    AttributeError:
        'Person' object has no attribute 'say_hello'
    

    because the test calls the say_hello function which does not yet exist in the Person object

  • I add a method definition for it to the Person object in src/person/__init__.py

    the terminal is my friend, and shows TypeError

    TypeError:
        Person.say_hello() takes 0 positional arguments
        but 2 were given
    

    because the definition for say_hello does not allow inputs and the test called the method with one positional argument (person). Why did the error say two were given when the test only sends one?

  • I add person to the method definition

    the terminal is my friend, and shows TypeError

    TypeError:
        Person.say_hello() takes 1 positional argument
        but 2 were given
    

    because methods take the copy of the object (self) they belong to as the first argument.


what is the staticmethod decorator?



REFACTOR: make it better


I want the say_hello method of the Person object to return a string for the person it receives, the same way the say_hello function returns a string for the person (dictionary) it receives as input



  • I add a calculation for the age with the year_of_birth attribute to the return statement of the say_hello method

    the terminal is my friend, and shows AttributeError

    AttributeError:
        'Person' object has no attribute 'year_of_birth'
    

    because there is no definition for year_of_birth in the Person object definition

  • I add an attribute to the Person object for year_of_birth

    the terminal is my friend, and shows AssertionError

    AssertionError:
        'Hello, my name is joe blow and I am YY'
     != 'Hello, my name is joe blow and I am XX'
    

    because I used a fixed value (1991) and the first assertion of the test expects datetime.datetime.now().year-1996. I have to get the value from the object that is passed to the say_hello method.

  • I add a variable to the __init__ method to use it to allow changing the year_of_birth attribute anytime a copy of the Person object is made

    the terminal still shows AssertionError

    AssertionError:
        'Hello, my name is joe blow and I am YY'
     != 'Hello, my name is joe blow and I am XX'
    
  • I change year_of_birth to an object attribute in the __init__ method by adding self. before it

    the test passes. What a beautiful life.

  • self.first_name, self.last_name and self.year_of_birth are now defined twice in the object. I remove the first definition since the attributes are also made in the __init__ method and that gets called when copies of the Person object are made, no need to have a default person be jane doe born in 1991

    the test is still green.

  • datetime.datetime.today().year gets used to calculate the age in the say_hello method of the Person object and the return statement of the person function. I make a helper function to calculate the age, the same way I do in the tests

     1import datetime
     2
     3
     4def calculate_age(year_of_birth):
     5    return (
     6        datetime.datetime.today().year
     7      - year_of_birth
     8    )
     9
    10
    11def say_hello(a_dictionary):
    
  • I use the new function for the age calculation in the person function

    still green.

  • I use the new function for the age calculation in the say_hello method of the Person object

    green.

  • The say_hello method is in the Person object, there is no need for it to take a copy of the Person object as input since it should be able to access the attributes of the object it belongs to. I change person. to self. to use object attributes instead

    the terminal is my friend, and shows NameError

    NameError: name 'self' is not defined
    
  • I change the name of the input parameter from person to self

    the test is green again.

  • I remove the staticmethod decorator because I no longer need it since the say_hello method is using object attributes

    the test is still green.

  • I change the call to src.person.say_hello(joe) for joe because I can call methods directly from a copy of an object, in test_classy_person_says_hello in test_person.py

    still green.

  • I change the call to src.person.say_hello(joe) for jane as well

    green.

  • I add an assertion for the next person

    the terminal is my friend, and shows AssertionError

    AssertionError:
        'Hello, my name is john smith and I am AAA'
     != 'Hello, my name is jane doe and I am YY'
    
  • I change my_expectation to match reality for john

    the test passes.

  • I add an assertion for mary

    the terminal is my friend, and shows AssertionError

    AssertionError:
        'Hello, my name is mary public and I am ZZ'
     != 'Hello, my name is john smith and I am AAA'
    
  • I change my_expectation to match reality for mary

    the test passes.

  • I open a new terminal then change directories to person

    terminal
    cd person
    
  • I add a git commit message in the other terminal

    terminal
    git commit -am 'add test_classy_person_says_hello'
    

test_classy_person_says_hello with random values

I want to use random values to test_classy_person_says_hello

  • I go back to the terminal where the tests are running

  • I add variables

  • I use the variables to remove repetition of 'joe', 'blow' and 1996

    the test is still green.

  • I add variables

  • I use the variables to remove repetition of 'jane' and 1991

    the test is still green.

  • I do the same thing with john

    the test is still green.

  • I do the same thing with mary

    the test is still green

  • I can add a random person with random values for the first_name, last_name and age variables that are sent in the call to src.person.Person to replace joe, jane, john and mary since they are all made the same way

    the terminal is my friend and shows AssertionError

    AssertionError: 'Hello, my name is Z Y and I am X' != ''
    
  • I change my_expectation to match reality for a_random_person

    the test passes.

  • I remove the commented lines and the other people from test_classy_person_says_hello because a_random_person covers their cases

  • I add a git commit message in the other terminal

    terminal
    git commit -am \
    'test_classy_person_says_hello with random values'
    

extract random_first_name object attribute

I make the values for first_name in the tests the same way each time, since TestPerson is an object, I can use an object attribute to remove repetition of how I make it, then have all the methods reference it


extract random_year_of_birth object attribute

I call the get_random_year_of_birth function for year_of_birth in each test, since TestPerson is an object, I can use an object attribute to remove repetition of those calls, then have all the methods reference the value it returns

  • I go back to the terminal where the tests are running

  • I add an object attribute called random_year_of_birth to the TestPerson object

  • I use self.random_year_of_birth in test_factory_w_keyword_arguments

    still green.

  • I use self.random_year_of_birth in test_factory_w_optional_arguments

    still green.

  • I use self.random_year_of_birth in test_factory_person_says_hello

    still green.

  • I use self.random_year_of_birth in test_classy_person_says_hello

    still green.

  • I add a git commit message in the other terminal

    terminal
    git commit -am \
    'extract random_year_of_birth object attribute'
    

extract random_last_name object attribute

The last_name variable is made the same way in three of the four tests, I can use an object attribute to remove its repetition then have all the methods reference the value

  • I go back to the terminal where the tests are running

  • I add an object attribute called random_last_name to the TestPerson object

  • I use self.random_last_name in test_factory_w_keyword_arguments

    green.

  • I use self.random_last_name in test_factory_person_says_hello

    green.

  • I use self.random_last_name in test_classy_person_says_hello

    green.

  • I add a git commit message in the other terminal

    terminal
    git commit -am \
    'extract random_last_name object attribute'
    

extract age object attribute

I call the calculate_age function with the self.random_year_of_birth attribute in each test, since TestPerson is an object, I can use an object attribute to remove repetition of those calls, then have all the methods reference the value it returns

  • I go back to the terminal where the tests are running

  • I add an object attribute called age to the TestPerson object

  • I use self.age in test_factory_w_keyword_arguments

    still green.

  • I remove the commented lines and unused variables from test_factory_w_keyword_arguments

  • I use self.age in test_factory_w_optional_arguments

    still green.

  • I remove the commented lines and unused variables from test_factory_w_optional_arguments

  • I use self.age in test_factory_person_says_hello

    still green.

  • I remove the commented lines and unused variables from test_factory_person_says_hello

    I remove the sex variable and parameter because it is not used in this test. I guess a_random_person is not all that random since it will always have 'M' as sex in this test.

  • I use self.age in test_classy_person_says_hello

    still green.

  • I remove the commented lines and unused variables from test_classy_person_says_hello

    I also do not need the sex variable and parameter in this test.

  • I add a git commit message in the other terminal

    terminal
    git commit -am \
    'extract age object attribute'
    

I can remove repetition with object attributes


how to use the setUp method to reset object attributes for every test

A problem with the current setup with the object attributes is that they are made once when the object is initialized. This means that even though they all use random values, those values are created once and every test that references the values after that is using the exact same values for each test.

I want each test to get new random values every time they run and the unittest.TestCase class has a way to do that - the `setUp method`_, it runs before every test is run.


RED: make it fail


  • I go back to the terminal where the tests are running

  • I add the `unittest.TestCase.setUp method`_ to TestPerson then move the object attributes into it

    the terminal is my friend, and shows AttributeError

    FAILED ...test_classy_person_says_hello -
        AttributeError: 'TestPerson' object has
        no attribute 'random_first_name'
    FAILED ...test_factory_person_says_hello -
        AttributeError: 'TestPerson' object has
        no attribute 'random_first_name'
    FAILED ...test_factory_w_keyword_arguments -
        AttributeError: 'TestPerson' object has
        no attribute 'random_first_name'
    FAILED ...test_factory_w_optional_arguments -
        AttributeError: 'TestPerson' object has
        no attribute 'random_first_name'
    

    because the first_name variable now belongs to the `setUp method`_, the other methods have no way to reach it. I have to make it an object attribute.


GREEN: make it pass


  • I change the first_name variable to an object attribute in the `setUp method`_ for the test methods to be able to use it

    the terminal is my friend, and shows AttributeError

    FAILED ...test_classy_person_says_hello - AttributeError:
        'TestPerson' object has no attribute 'random_last_name'.
        Did you mean: 'random_first_name'?
    FAILED ...test_factory_person_says_hello - AttributeError:
        'TestPerson' object has no attribute 'random_last_name'.
        Did you mean: 'random_first_name'?
    FAILED ...test_factory_w_keyword_arguments - AttributeError:
        'TestPerson' object has no attribute 'random_last_name'.
        Did you mean: 'random_first_name'?
    FAILED ...test_factory_w_optional_arguments -
        AttributeError: 'TestPerson' object has
        no attribute 'random_year_of_birth'.
    

    because the year_of_birth and last_name variables now belong to the `setUp method`_, the other methods have no way to reach them. I have to make them object attributes

  • I change the year_of_birth and last_name variables to object attributes in the `setUp method`_ for the test methods to be able to use them as well

    the terminal is my friend, and shows AttributeError

    FAILED ...test_classy_person_says_hello -
        AttributeError: 'TestPerson' object has
        no attribute 'age'
    FAILED ...test_factory_person_says_hello -
        AttributeError: 'TestPerson' object has
        no attribute 'age'
    FAILED ...test_factory_w_keyword_arguments -
        AttributeError: 'TestPerson' object has
        no attribute 'age'
    FAILED ...test_factory_w_optional_arguments -
        AttributeError: 'TestPerson' object has
        no attribute 'age'
    

    because the age belongs to the `setUp method`_, and the other methods have no way to reach it. I have to make it an object attribute

  • I change the age variable to object attributes in the `setUp method`_ for the other methods to be able to use it

    the test passes.

The `unittest.TestCase.setUp method`_ runs before every test, in this case it sets these object attributes (variables) to new values before every test

  • self.random_first_name to the result of calling the get_random_name function, which returns a random name

  • self.random_last_name to the result of calling the get_random_name function, which returns a random name

  • self.random_year_of_birth to the result of calling the get_random_year_of_birth function which returns a random year between 120 years ago and the current year

  • self.age to the result of calling the calculate_age function, which returns the current year minus self.random_year_of_birth


REFACTOR: make it better


  • I no longer need the calculate_age function because it is only called by the `setUp method`_. I use `datetime.datetime.now`_ directly

    the test is still green.

  • I no longer need the get_random_year_of_birth function because it is only called by the `setUp method`_. I use random.randint directly

    still green.

  • I use the this_year variable in the calculation for self.age

    green. datetime.datetime.now().year is now called once each time the `setUp method`_ runs

  • I remove the commented lines

  • I remove the calculate_age and get_random_year_of_birth functions

     1import datetime
     2import random
     3import src.person
     4import unittest
     5
     6
     7def pick_one(*choices):
     8    return random.choice(choices)
     9
    10
    11def get_random_name():
    12    return pick_one(
    13        'jane', 'joe', 'john', 'person',
    14        'doe', 'smith', 'blow', 'public',
    15    )
    16
    17
    18class TestPerson(unittest.TestCase):
    
  • I add a git commit message in the other terminal

    terminal
    git commit -am 'move object attributes to setUp method'
    

test_dir_person_instance

Python has the dir built-in function which shows the attributes and methods of the object it is given in parentheses. It allows me to see what makes up an object without looking at the code or reading the documentation. I can then run tests to see what each thing does.


RED: make it fail


  • I go back to the terminal where the tests are running

  • I add a new test with the dir built-in function in test_person.py

    the terminal is my friend, and shows AssertionError

    AssertionError: Lists differ:
        ['__class__', '__delattr__', '__dict__',
         '[377 chars]llo']
     != None
    

    because dir returned a list (anything in square brackets [ ]) and my_expectation is None


GREEN: make it pass


  • I copy (ctrl/command+c) the values from the terminal and paste (ctrl/command+v) them as my_expectation

    the terminal is my friend, and shows SyntaxError

    E       [371 chars]llo'
    E                     ^
    E   SyntaxError: unterminated string literal
                     (detected at line 94)
    

    because I have a closing quote (') without a matching opening one and enclosures must be closed once open

  • I add the opening quote

    the terminal is my friend and shows AssertionError

    AssertionError: Lists differ:
        ['__c[32 chars]_', '__dir__', '__doc__', '__eq__',
         '__firstli[329 chars]llo']
     != ['__c[32 chars]_', '[371 chars]llo']
    

    it shows me the entire list below the message

  • I copy (ctrl/command+c) the values from the terminal and paste (ctrl/command+v) them as my_expectation

    the terminal shows NameError

    NameError: name 'E' is not defined
    
  • I use the find and replace feature of the Integrated Development Environment (IDE) to remove the extra characters, then remove the commented lines

    • the test passes.

    • the __init__ and say_hello methods I defined are in the list

    • there are names in the list that I did not define, which leads to the question of where did they come from?

    • The attributes I defined in the __init__ method are not in the list, because the test called dir on src.person.Person which is the object, not an instance (copy) of the class

  • I add a git commit message in the other terminal

    terminal
    git commit -am \
    'add test_dir_person_object'
    

test_dir_person_object

RED: make it fail


I add a test for the attributes and methods of an instance/copy of the Person object to see the difference between it and the original

118            '__str__',
119            '__subclasshook__',
120            '__weakref__',
121            'say_hello',
122        ]
123        self.assertEqual(reality, my_expectation)
124
125    def test_dir_person_instance(self):
126        an_instance_of_person = src.person.Person(
127            first_name=self.random_first_name,
128            last_name=self.random_last_name,
129            year_of_birth=self.random_year_of_birth,
130            sex=pick_one('F', 'M')
131        )
132
133        reality = dir(an_instance_of_person)
134        my_expectation = [
135            '__class__',
136            '__delattr__',
137            '__dict__',
138            '__dir__',
139            '__doc__',
140            '__eq__',
141            '__firstlineno__',
142            '__format__',
143            '__ge__',
144            '__getattribute__',
145            '__getstate__',
146            '__gt__',
147            '__hash__',
148            '__init__',
149            '__init_subclass__',
150            '__le__',
151            '__lt__',
152            '__module__',
153            '__ne__',
154            '__new__',
155            '__reduce__',
156            '__reduce_ex__',
157            '__repr__',
158            '__setattr__',
159            '__sizeof__',
160            '__static_attributes__',
161            '__str__',
162            '__subclasshook__',
163            '__weakref__',
164            'say_hello',
165        ]
166        self.assertEqual(reality, my_expectation)
167
168
169# Exceptions

the terminal is my friend, and shows AssertionError

AssertionError: Lists differ:
    ['__c[393 chars]ef__', 'first_name', 'last_name',
      'say_hello', 'year_of_birth']
 != ['__c[393 chars]ef__', 'say_hello']

because first_name, last_name and year_of_birth are missing. Why is there no sex?


GREEN: make it pass


I add the missing attributes to my_expectation

133        reality = dir(an_instance_of_person)
134        my_expectation = [
135            '__class__',
136            '__delattr__',
137            '__dict__',
138            '__dir__',
139            '__doc__',
140            '__eq__',
141            '__firstlineno__',
142            '__format__',
143            '__ge__',
144            '__getattribute__',
145            '__getstate__',
146            '__gt__',
147            '__hash__',
148            '__init__',
149            '__init_subclass__',
150            '__le__',
151            '__lt__',
152            '__module__',
153            '__ne__',
154            '__new__',
155            '__reduce__',
156            '__reduce_ex__',
157            '__repr__',
158            '__setattr__',
159            '__sizeof__',
160            '__static_attributes__',
161            '__str__',
162            '__subclasshook__',
163            '__weakref__',
164            'first_name',
165            'last_name',
166            'say_hello',
167            'year_of_birth',
168        ]
169        self.assertEqual(reality, my_expectation)
170
171
172# Exceptions seen

the test passes.


REFACTOR: make it better


  • I add sex to the list

    the terminal is my friend, and shows AssertionError

    AssertionError: Lists differ:
        ['__c[400 chars]'first_name', 'last_name',
         'say_hello', 'year_of_birth']
     != ['__c[400 chars]'first_name', 'last_name',
         'say_hello', 'sex', 'year_of_birth']
    

    the sex attribute is not defined anywhere in the Person object

  • I add self.sex to the __init__ method of the Person object in src/person/__init__.py

    the test passes

  • I remove the commented lines

     1import datetime
     2
     3
     4def calculate_age(year_of_birth):
     5    return (
     6        datetime.datetime.today().year
     7      - year_of_birth
     8    )
     9
    10
    11def say_hello(a_dictionary):
    12    return (
    13        f'Hello, my name is {a_dictionary.get("first_name")}'
    14        f' {a_dictionary.get("last_name")}'
    15        f' and I am {a_dictionary.get("age")}'
    16    )
    17
    18
    19def person(
    20        first_name, year_of_birth,
    21        last_name='doe', sex='M',
    22    ):
    23    return {
    24        'first_name': first_name,
    25        'last_name': last_name,
    26        'sex': sex,
    27        'age': calculate_age(year_of_birth),
    28    }
    29
    30
    31class Person:
    32
    33    def __init__(
    34        self, first_name, last_name='doe',
    35        year_of_birth=None, sex=None,
    36    ):
    37        self.first_name = first_name
    38        self.last_name = last_name
    39        self.year_of_birth = year_of_birth
    40        self.sex = sex
    41        return None
    42
    43    def say_hello(self):
    44        age = calculate_age(self.year_of_birth)
    45        return (
    46            f'Hello, my name is {self.first_name}'
    47            f' {self.last_name}'
    48            f' and I am {age}'
    49        )
    
  • I add a git commit message in the other terminal

    terminal
    git commit -am \
    'add test_dir_person_instance'
    

close the project

  • I close test_person.py and src/person/__init__.py

  • I click in the terminal where the tests are running

  • I use q on the keyboard to leave the tests. The terminal goes back to the command line.

  • I change directory to the parent of person

    terminal
    cd ..
    

    the terminal shows

    .../pumping_python
    

    I am back in the pumping_python directory.


code from the chapter

Do you want to see all the CODE I typed in this chapter?


review

There are few problems with what I have now

  • anyone seeing the tests for the first time has to read the object attributes

    class TestPerson(unittest.TestCase):
    
        def setUp(self):
            self.random_first_name = get_random_name()
            self.random_last_name = get_random_name()
            this_year = datetime.datetime.now().year
            self.random_year_of_birth = random.randint(
                this_year-120, this_year
            )
            self.age = this_year - self.random_year_of_birth
    
        def test_factory_w_keyword_arguments(self):
    

    to know how they are created then referenced in each test

  • test_factory_w_keyword_arguments needs the person reading the test to know about double starred expressions

    src.person.person(
        **a_person,
        year_of_birth=self.random_year_of_birth,
    )
    
    dict(
        **a_person,
        age=self.age,
    )
    

    to know why using the dictionary works in the call to src.person.person and inside another dictionary

  • test_factory_person_says_hello and test_classy_person_says_hello need the person reading the test to know about f-strings

    f'Hello, my name is {self.random_first_name}'
    f' {self.random_last_name} '
    f'and I am {self.age}'
    

To review

Tip

  • If I find myself writing or doing the same thing two times, I write a function

  • If I find I have two functions that use the same information, I write an object

How many questions can you answer about objects?


what is next?

You have gone through a lot of things and know:

Would you like to test what causes AttributeError or Would you like to know where the extra attributes and methods of the Person object came from?

You know enough to go into the world and use Python. If you stopped going through the book at this point, you would be fine because you know how to make objects, functions and can make dictionaries which is what is behind a lot of the things you will encounter.


rate pumping python

If this has been a 7 star experience for you, please CLICK HERE to leave a 5 star review of pumping python. It helps other people get into the book too.