Skip to content

Commit f246fde

Browse files
committed
rfctr: improve typing
1 parent e493474 commit f246fde

32 files changed

+501
-461
lines changed

features/steps/coreprops.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from datetime import datetime, timedelta
44

55
from behave import given, then, when
6+
from behave.runner import Context
67

78
from docx import Document
89
from docx.opc.coreprops import CoreProperties
@@ -13,25 +14,25 @@
1314

1415

1516
@given("a document having known core properties")
16-
def given_a_document_having_known_core_properties(context):
17+
def given_a_document_having_known_core_properties(context: Context):
1718
context.document = Document(test_docx("doc-coreprops"))
1819

1920

2021
@given("a document having no core properties part")
21-
def given_a_document_having_no_core_properties_part(context):
22+
def given_a_document_having_no_core_properties_part(context: Context):
2223
context.document = Document(test_docx("doc-no-coreprops"))
2324

2425

2526
# when ====================================================
2627

2728

2829
@when("I access the core properties object")
29-
def when_I_access_the_core_properties_object(context):
30+
def when_I_access_the_core_properties_object(context: Context):
3031
context.document.core_properties
3132

3233

3334
@when("I assign new values to the properties")
34-
def when_I_assign_new_values_to_the_properties(context):
35+
def when_I_assign_new_values_to_the_properties(context: Context):
3536
context.propvals = (
3637
("author", "Creator"),
3738
("category", "Category"),
@@ -58,7 +59,7 @@ def when_I_assign_new_values_to_the_properties(context):
5859

5960

6061
@then("a core properties part with default values is added")
61-
def then_a_core_properties_part_with_default_values_is_added(context):
62+
def then_a_core_properties_part_with_default_values_is_added(context: Context):
6263
core_properties = context.document.core_properties
6364
assert core_properties.title == "Word Document"
6465
assert core_properties.last_modified_by == "python-docx"
@@ -71,14 +72,14 @@ def then_a_core_properties_part_with_default_values_is_added(context):
7172

7273

7374
@then("I can access the core properties object")
74-
def then_I_can_access_the_core_properties_object(context):
75+
def then_I_can_access_the_core_properties_object(context: Context):
7576
document = context.document
7677
core_properties = document.core_properties
7778
assert isinstance(core_properties, CoreProperties)
7879

7980

8081
@then("the core property values match the known values")
81-
def then_the_core_property_values_match_the_known_values(context):
82+
def then_the_core_property_values_match_the_known_values(context: Context):
8283
known_propvals = (
8384
("author", "Steve Canny"),
8485
("category", "Category"),
@@ -106,7 +107,7 @@ def then_the_core_property_values_match_the_known_values(context):
106107

107108

108109
@then("the core property values match the new values")
109-
def then_the_core_property_values_match_the_new_values(context):
110+
def then_the_core_property_values_match_the_new_values(context: Context):
110111
core_properties = context.document.core_properties
111112
for name, expected_value in context.propvals:
112113
value = getattr(core_properties, name)

src/docx/enum/__init__.py

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +0,0 @@
1-
"""Enumerations used in python-docx."""
2-
3-
4-
class Enumeration:
5-
@classmethod
6-
def from_xml(cls, xml_val):
7-
return cls._xml_to_idx[xml_val]
8-
9-
@classmethod
10-
def to_xml(cls, enum_val):
11-
return cls._idx_to_xml[enum_val]

src/docx/image/image.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def height(self) -> Inches:
114114
return Inches(self.px_height / self.vert_dpi)
115115

116116
def scaled_dimensions(
117-
self, width: int | None = None, height: int | None = None
117+
self, width: int | Length | None = None, height: int | Length | None = None
118118
) -> Tuple[Length, Length]:
119119
"""(cx, cy) pair representing scaled dimensions of this image.
120120

src/docx/opc/coreprops.py

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,44 +3,53 @@
33
These are broadly-standardized attributes like author, last-modified, etc.
44
"""
55

6+
from __future__ import annotations
7+
8+
from typing import TYPE_CHECKING
9+
10+
from docx.oxml.coreprops import CT_CoreProperties
11+
12+
if TYPE_CHECKING:
13+
from docx.oxml.coreprops import CT_CoreProperties
14+
615

716
class CoreProperties:
817
"""Corresponds to part named ``/docProps/core.xml``, containing the core document
918
properties for this document package."""
1019

11-
def __init__(self, element):
20+
def __init__(self, element: CT_CoreProperties):
1221
self._element = element
1322

1423
@property
1524
def author(self):
1625
return self._element.author_text
1726

1827
@author.setter
19-
def author(self, value):
28+
def author(self, value: str):
2029
self._element.author_text = value
2130

2231
@property
2332
def category(self):
2433
return self._element.category_text
2534

2635
@category.setter
27-
def category(self, value):
36+
def category(self, value: str):
2837
self._element.category_text = value
2938

3039
@property
3140
def comments(self):
3241
return self._element.comments_text
3342

3443
@comments.setter
35-
def comments(self, value):
44+
def comments(self, value: str):
3645
self._element.comments_text = value
3746

3847
@property
3948
def content_status(self):
4049
return self._element.contentStatus_text
4150

4251
@content_status.setter
43-
def content_status(self, value):
52+
def content_status(self, value: str):
4453
self._element.contentStatus_text = value
4554

4655
@property
@@ -56,31 +65,31 @@ def identifier(self):
5665
return self._element.identifier_text
5766

5867
@identifier.setter
59-
def identifier(self, value):
68+
def identifier(self, value: str):
6069
self._element.identifier_text = value
6170

6271
@property
6372
def keywords(self):
6473
return self._element.keywords_text
6574

6675
@keywords.setter
67-
def keywords(self, value):
76+
def keywords(self, value: str):
6877
self._element.keywords_text = value
6978

7079
@property
7180
def language(self):
7281
return self._element.language_text
7382

7483
@language.setter
75-
def language(self, value):
84+
def language(self, value: str):
7685
self._element.language_text = value
7786

7887
@property
7988
def last_modified_by(self):
8089
return self._element.lastModifiedBy_text
8190

8291
@last_modified_by.setter
83-
def last_modified_by(self, value):
92+
def last_modified_by(self, value: str):
8493
self._element.lastModifiedBy_text = value
8594

8695
@property
@@ -112,21 +121,21 @@ def subject(self):
112121
return self._element.subject_text
113122

114123
@subject.setter
115-
def subject(self, value):
124+
def subject(self, value: str):
116125
self._element.subject_text = value
117126

118127
@property
119128
def title(self):
120129
return self._element.title_text
121130

122131
@title.setter
123-
def title(self, value):
132+
def title(self, value: str):
124133
self._element.title_text = value
125134

126135
@property
127136
def version(self):
128137
return self._element.version_text
129138

130139
@version.setter
131-
def version(self, value):
140+
def version(self, value: str):
132141
self._element.version_text = value

src/docx/opc/oxml.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@
77
deleted or only hold the package related custom element classes.
88
"""
99

10+
from __future__ import annotations
11+
12+
from typing import cast
13+
1014
from lxml import etree
1115

1216
from docx.opc.constants import NAMESPACE as NS
@@ -138,7 +142,7 @@ class CT_Relationship(BaseOxmlElement):
138142
target part."""
139143

140144
@staticmethod
141-
def new(rId, reltype, target, target_mode=RTM.INTERNAL):
145+
def new(rId: str, reltype: str, target: str, target_mode: str = RTM.INTERNAL):
142146
"""Return a new ``<Relationship>`` element."""
143147
xml = '<Relationship xmlns="%s"/>' % nsmap["pr"]
144148
relationship = parse_xml(xml)
@@ -178,19 +182,18 @@ def target_mode(self):
178182
class CT_Relationships(BaseOxmlElement):
179183
"""``<Relationships>`` element, the root element in a .rels file."""
180184

181-
def add_rel(self, rId, reltype, target, is_external=False):
185+
def add_rel(self, rId: str, reltype: str, target: str, is_external: bool = False):
182186
"""Add a child ``<Relationship>`` element with attributes set according to
183187
parameter values."""
184188
target_mode = RTM.EXTERNAL if is_external else RTM.INTERNAL
185189
relationship = CT_Relationship.new(rId, reltype, target, target_mode)
186190
self.append(relationship)
187191

188192
@staticmethod
189-
def new():
193+
def new() -> CT_Relationships:
190194
"""Return a new ``<Relationships>`` element."""
191195
xml = '<Relationships xmlns="%s"/>' % nsmap["pr"]
192-
relationships = parse_xml(xml)
193-
return relationships
196+
return cast(CT_Relationships, parse_xml(xml))
194197

195198
@property
196199
def Relationship_lst(self):

src/docx/opc/package.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from __future__ import annotations
44

5-
from typing import IO, TYPE_CHECKING, Iterator
5+
from typing import IO, TYPE_CHECKING, Iterator, cast
66

77
from docx.opc.constants import RELATIONSHIP_TYPE as RT
88
from docx.opc.packuri import PACKAGE_URI, PackURI
@@ -14,7 +14,9 @@
1414
from docx.shared import lazyproperty
1515

1616
if TYPE_CHECKING:
17+
from docx.opc.coreprops import CoreProperties
1718
from docx.opc.part import Part
19+
from docx.opc.rel import _Relationship # pyright: ignore[reportPrivateUsage]
1820

1921

2022
class OpcPackage:
@@ -37,16 +39,18 @@ def after_unmarshal(self):
3739
pass
3840

3941
@property
40-
def core_properties(self):
42+
def core_properties(self) -> CoreProperties:
4143
"""|CoreProperties| object providing read/write access to the Dublin Core
4244
properties for this document."""
4345
return self._core_properties_part.core_properties
4446

45-
def iter_rels(self):
47+
def iter_rels(self) -> Iterator[_Relationship]:
4648
"""Generate exactly one reference to each relationship in the package by
4749
performing a depth-first traversal of the rels graph."""
4850

49-
def walk_rels(source, visited=None):
51+
def walk_rels(
52+
source: OpcPackage | Part, visited: list[Part] | None = None
53+
) -> Iterator[_Relationship]:
5054
visited = [] if visited is None else visited
5155
for rel in source.rels.values():
5256
yield rel
@@ -103,7 +107,7 @@ def main_document_part(self):
103107
"""
104108
return self.part_related_by(RT.OFFICE_DOCUMENT)
105109

106-
def next_partname(self, template):
110+
def next_partname(self, template: str) -> PackURI:
107111
"""Return a |PackURI| instance representing partname matching `template`.
108112
109113
The returned part-name has the next available numeric suffix to distinguish it
@@ -163,13 +167,13 @@ def save(self, pkg_file: str | IO[bytes]):
163167
PackageWriter.write(pkg_file, self.rels, self.parts)
164168

165169
@property
166-
def _core_properties_part(self):
170+
def _core_properties_part(self) -> CorePropertiesPart:
167171
"""|CorePropertiesPart| object related to this package.
168172
169173
Creates a default core properties part if one is not present (not common).
170174
"""
171175
try:
172-
return self.part_related_by(RT.CORE_PROPERTIES)
176+
return cast(CorePropertiesPart, self.part_related_by(RT.CORE_PROPERTIES))
173177
except KeyError:
174178
core_properties_part = CorePropertiesPart.default(self)
175179
self.relate_to(core_properties_part, RT.CORE_PROPERTIES)

src/docx/opc/packuri.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
Also some useful known pack URI strings such as PACKAGE_URI.
44
"""
55

6+
from __future__ import annotations
7+
68
import posixpath
79
import re
810

@@ -16,22 +18,21 @@ class PackURI(str):
1618

1719
_filename_re = re.compile("([a-zA-Z]+)([1-9][0-9]*)?")
1820

19-
def __new__(cls, pack_uri_str):
21+
def __new__(cls, pack_uri_str: str):
2022
if pack_uri_str[0] != "/":
2123
tmpl = "PackURI must begin with slash, got '%s'"
2224
raise ValueError(tmpl % pack_uri_str)
2325
return str.__new__(cls, pack_uri_str)
2426

2527
@staticmethod
26-
def from_rel_ref(baseURI, relative_ref):
27-
"""Return a |PackURI| instance containing the absolute pack URI formed by
28-
translating `relative_ref` onto `baseURI`."""
28+
def from_rel_ref(baseURI: str, relative_ref: str) -> PackURI:
29+
"""The absolute PackURI formed by translating `relative_ref` onto `baseURI`."""
2930
joined_uri = posixpath.join(baseURI, relative_ref)
3031
abs_uri = posixpath.abspath(joined_uri)
3132
return PackURI(abs_uri)
3233

3334
@property
34-
def baseURI(self):
35+
def baseURI(self) -> str:
3536
"""The base URI of this pack URI, the directory portion, roughly speaking.
3637
3738
E.g. ``'/ppt/slides'`` for ``'/ppt/slides/slide1.xml'``. For the package pseudo-
@@ -40,9 +41,8 @@ def baseURI(self):
4041
return posixpath.split(self)[0]
4142

4243
@property
43-
def ext(self):
44-
"""The extension portion of this pack URI, e.g. ``'xml'`` for
45-
``'/word/document.xml'``.
44+
def ext(self) -> str:
45+
"""The extension portion of this pack URI, e.g. ``'xml'`` for ``'/word/document.xml'``.
4646
4747
Note the period is not included.
4848
"""
@@ -84,7 +84,7 @@ def membername(self):
8484
"""
8585
return self[1:]
8686

87-
def relative_ref(self, baseURI):
87+
def relative_ref(self, baseURI: str):
8888
"""Return string containing relative reference to package item from `baseURI`.
8989
9090
E.g. PackURI('/ppt/slideLayouts/slideLayout1.xml') would return

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy