Skip to content

vector

mypackage.vector.vector

This module contains the Vector class and the NormError exception.

Attributes:

Name Type Description
MAX_NORM float

Maximum norm allowed for a Vector instance.

Note

Imports should follow always the same order: import python_standard_library

import third_party_libraries

import local_librariess

NormError(norm)

Bases: ValueError

Exception raised when a vector's norm is greater than MAX_NORM.

Note

Custom exception classes are very useful for exception handling.

Parameters:

Name Type Description Default
norm float

The norm of the vector.

required

Attributes:

Name Type Description
message str

The message to display when the exception is raised.

Source code in mypackage/vector/vector.py
41
42
43
def __init__(self, norm: float) -> None:
    message = f"Norm = {norm}, but it cannot be greater than {MAX_NORM}."
    super().__init__(message)

Vector(x, y)

Two dimensional vector.

Note

Remember that class docstrings in Google format should contain the arguments of the init method and the attributes of the class, but not the methods.

Parameters:

Name Type Description Default
x float

first component of the vector.

required
y float

second component of the vector.

required

Attributes:

Name Type Description
x float

first component of the vector.

y float

second component of the vector.

Raises:

Type Description
NormError

the norm of the vector is greater than MAX_NORM.

Source code in mypackage/vector/vector.py
65
66
67
68
69
70
def __init__(self, x: float, y: float) -> None:
    self.x: float = x
    self.y: float = y

    if self.norm > MAX_NORM:
        raise NormError(self.norm)

norm: float property

Returns the Euclidean norm of the vector.

Note

Since the method doesn't accept any input, we can treat it as an attribute. To do that we just have to add the @property decorator on top of the method.

Returns:

Name Type Description
float float

the euclidean norm of the vector.

Examples:

>>> vector = Vector(1,0)
>>> vector.norm
1.0

__add__(other_vector)

Returns the addition vector of self and the other vector.

Parameters:

Name Type Description Default
other_vector Vector

Other vector (right hand side).

required

Raises:

Type Description
TypeError

Not Vector passed in.

Returns:

Type Description
Vector

The addition vector of self and the other vector.

Examples:

>>> Vector(1, 0) + Vector(0, 1)
Vector(1, 1)
Source code in mypackage/vector/vector.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def __add__(self, other_vector: Vector) -> Vector:
    """Returns the addition vector of self and the other vector.

    Args:
        other_vector: Other vector (right hand side).

    Raises:
        TypeError: Not Vector passed in.

    Returns:
        The addition vector of self and the other vector.

    Examples:

        >>> Vector(1, 0) + Vector(0, 1)
        Vector(1, 1)

    """
    if not isinstance(other_vector, Vector):
        raise TypeError("You must pass in a Vector instance!")
    x = self.x + other_vector.x
    y = self.y + other_vector.y
    return Vector(x, y)

__eq__(other_vector)

Check if the vectors have the same values up to some tolerance.

Parameters:

Name Type Description Default
other_vector object

Other vector (right hand side).

required

Returns:

Type Description
bool

True, if both vectors have the same values.

bool

False, else.

Examples:

>>> Vector(1, 0) == Vector(2, 0)
False
Source code in mypackage/vector/vector.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def __eq__(self, other_vector: object) -> bool:
    """Check if the vectors have the same values up to some tolerance.

    Args:
        other_vector: Other vector (right hand side).

    Returns:
        True, if both vectors have the same values.
        False, else.

    Examples:

        >>> Vector(1, 0) == Vector(2, 0)
        False

    """
    if not isinstance(other_vector, Vector):
        return False
    # math.isclose returns true if the numbers are equal up to a small error
    equal_x: bool = math.isclose(self.x, other_vector.x, abs_tol=1e-10)
    equal_y: bool = math.isclose(self.y, other_vector.y, abs_tol=1e-10)
    return equal_x and equal_y

__mul__(other)

Return the multiplication of self and the other vector/number.

Parameters:

Name Type Description Default
other Vector | float

Other vector or scalar value (right hand side).

required

Raises:

Type Description
TypeError

Not int/float passed in.

Returns:

Type Description
Vector | float

The multiplication of self and the other vector/number.

Examples:

>>> Vector(1, 0) * 4
Vector(4, 0)
>>> Vector(1, 0) * Vector(1, 1)
1
Source code in mypackage/vector/vector.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def __mul__(self, other: Vector | float) -> Vector | float:
    """Return the multiplication of self and the other vector/number.

    Args:
        other: Other vector or scalar value (right hand side).

    Raises:
        TypeError: Not int/float passed in.

    Returns:
        The multiplication of self and the other vector/number.

    Examples:

        >>> Vector(1, 0) * 4
        Vector(4, 0)

        >>> Vector(1, 0) * Vector(1, 1)
        1

    """
    if isinstance(other, Vector):
        return self.x * other.x + self.y * other.y

    if not isinstance(other, int | float):
        raise TypeError("You must pass in an int/float!")

    return Vector(self.x * other, self.y * other)

__repr__()

Return the vector representation.

Note

The idea behind representations is that, when we execute the output of this function, we should create an identical copy of this object.

Returns:

Type Description
str

The representation of the vector.

Examples:

We type the following to output the vector representation:

>>> vector = Vector(1, 2)
>>> vector
Vector(1, 2)
Source code in mypackage/vector/vector.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __repr__(self) -> str:
    """Return the vector representation.

    Note:
        The idea behind representations is that, when we execute the output of this
        function, we should create an identical copy of this object.

    Returns:
        The representation of the vector.

    Examples:
        We type the following to output the vector representation:

        >>> vector = Vector(1, 2)
        >>> vector
        Vector(1, 2)

    """
    return f"Vector({self.x}, {self.y})"

__str__()

This method is called when we want to print our vector as a string.

Returns:

Type Description
str

The vector instance as a string.

Examples:

To call str simply type

>>> vector = Vector(1, 2)
>>> print(vector)
(1, 2)
Source code in mypackage/vector/vector.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def __str__(self) -> str:
    """This method is called when we want to print our vector as a string.

    Returns:
        The vector instance as a string.

    Examples:
        To call __str__ simply type

        >>> vector = Vector(1, 2)
        >>> print(vector)
        (1, 2)

    """
    return f"({self.x}, {self.y})"

projection(subspace=None)

By default projects the vector onto its first component. If a vector spanning a subspace is given, then the vector is projected along this subspace.

Parameters:

Name Type Description Default
subspace Vector

vector that spans the subspace onto which to project the vector. Defaults to None.

None

Returns:

Name Type Description
Vector Vector

The projected vector.

Examples:

>>> Vector(1,1).projection(Vector(0,1))
Vector(0.0, 1.0)
Source code in mypackage/vector/vector.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def projection(self, subspace: Vector | None = None) -> Vector:
    """By default projects the vector onto its first component. If a vector spanning
    a subspace is given, then the vector is projected along this subspace.

    Args:
        subspace (Vector, optional): vector that spans the subspace onto which to project
            the vector. Defaults to None.

    Returns:
        Vector: The projected vector.

    Examples:
        >>> Vector(1,1).projection(Vector(0,1))
        Vector(0.0, 1.0)

    """
    if subspace is None:
        warnings.warn(
            "No subspace given: the vector is projected onto the first component!", stacklevel=2
        )
        return Vector(self.x, 0)
    else:
        # Note that self is the instance of the Vector class
        projection_coef: float = (subspace * self) / subspace.norm**2
        return subspace * projection_coef