Skip to content

dsm

dependenpy dsm module.

This is the core module of dependenpy. It contains the following classes:

  • DSM: to create a DSM-capable object for a list of packages,
  • Package: which represents a Python package,
  • Module: which represents a Python module,
  • Dependency: which represents a dependency between two modules.

DSM ¤

Bases: RootNode, NodeMixin, PrintMixin

DSM-capable class.

Technically speaking, a DSM instance is not a real DSM but more a tree representing the Python packages structure. However, it has the necessary methods to build a real DSM in the form of a square matrix, a dictionary or a tree-map.

Source code in dependenpy/dsm.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
class DSM(RootNode, NodeMixin, PrintMixin):
    """
    DSM-capable class.

    Technically speaking, a DSM instance is not a real DSM but more a tree
    representing the Python packages structure. However, it has the
    necessary methods to build a real DSM in the form of a square matrix,
    a dictionary or a tree-map.
    """

    def __init__(
        self, *packages: str, build_tree: bool = True, build_dependencies: bool = True, enforce_init: bool = True
    ):
        """
        Initialization method.

        Args:
            *packages: list of packages to search for.
            build_tree: auto-build the tree or not.
            build_dependencies: auto-build the dependencies or not.
            enforce_init: if True, only treat directories if they contain an `__init__.py` file.
        """
        self.base_packages = packages
        self.finder = Finder()
        self.specs = []
        self.not_found = []
        self.enforce_init = enforce_init

        specs = []
        for package in packages:
            spec = self.finder.find(package, enforce_init=enforce_init)
            if spec:
                specs.append(spec)
            else:
                self.not_found.append(package)

        if not specs:
            print("** dependenpy: DSM empty.", file=sys.stderr)

        self.specs = PackageSpec.combine(specs)

        for module in self.not_found:
            print(f"** dependenpy: Not found: {module}.", file=sys.stderr)

        super().__init__(build_tree)

        if build_tree and build_dependencies:
            self.build_dependencies()

    def __str__(self):
        packages_names = ", ".join([package.name for package in self.packages])
        return f"Dependency DSM for packages: [{packages_names}]"

    @property
    def isdsm(self) -> bool:
        """
        Inherited from NodeMixin. Always True.

        Returns:
            Whether this object is a DSM.
        """
        return True

    def build_tree(self):
        """Build the Python packages tree."""
        for spec in self.specs:
            if spec.ismodule:
                self.modules.append(Module(spec.name, spec.path, dsm=self))
            else:
                self.packages.append(
                    Package(
                        spec.name,
                        spec.path,
                        dsm=self,
                        limit_to=spec.limit_to,
                        build_tree=True,
                        build_dependencies=False,
                        enforce_init=self.enforce_init,
                    )
                )

__init__(*packages, build_tree=True, build_dependencies=True, enforce_init=True) ¤

Initialization method.

Parameters:

Name Type Description Default
*packages str

list of packages to search for.

()
build_tree bool

auto-build the tree or not.

True
build_dependencies bool

auto-build the dependencies or not.

True
enforce_init bool

if True, only treat directories if they contain an __init__.py file.

True
Source code in dependenpy/dsm.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def __init__(
    self, *packages: str, build_tree: bool = True, build_dependencies: bool = True, enforce_init: bool = True
):
    """
    Initialization method.

    Args:
        *packages: list of packages to search for.
        build_tree: auto-build the tree or not.
        build_dependencies: auto-build the dependencies or not.
        enforce_init: if True, only treat directories if they contain an `__init__.py` file.
    """
    self.base_packages = packages
    self.finder = Finder()
    self.specs = []
    self.not_found = []
    self.enforce_init = enforce_init

    specs = []
    for package in packages:
        spec = self.finder.find(package, enforce_init=enforce_init)
        if spec:
            specs.append(spec)
        else:
            self.not_found.append(package)

    if not specs:
        print("** dependenpy: DSM empty.", file=sys.stderr)

    self.specs = PackageSpec.combine(specs)

    for module in self.not_found:
        print(f"** dependenpy: Not found: {module}.", file=sys.stderr)

    super().__init__(build_tree)

    if build_tree and build_dependencies:
        self.build_dependencies()

build_tree() ¤

Build the Python packages tree.

Source code in dependenpy/dsm.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def build_tree(self):
    """Build the Python packages tree."""
    for spec in self.specs:
        if spec.ismodule:
            self.modules.append(Module(spec.name, spec.path, dsm=self))
        else:
            self.packages.append(
                Package(
                    spec.name,
                    spec.path,
                    dsm=self,
                    limit_to=spec.limit_to,
                    build_tree=True,
                    build_dependencies=False,
                    enforce_init=self.enforce_init,
                )
            )

isdsm() property ¤

Inherited from NodeMixin. Always True.

Returns:

Type Description
bool

Whether this object is a DSM.

Source code in dependenpy/dsm.py
80
81
82
83
84
85
86
87
88
@property
def isdsm(self) -> bool:
    """
    Inherited from NodeMixin. Always True.

    Returns:
        Whether this object is a DSM.
    """
    return True

Dependency ¤

Bases: object

Dependency class.

Represent a dependency from a module to another.

Source code in dependenpy/dsm.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
class Dependency(object):
    """
    Dependency class.

    Represent a dependency from a module to another.
    """

    def __init__(self, source, lineno, target, what=None):
        """
        Initialization method.

        Args:
            source (Module): source Module.
            lineno (int): number of line at which import statement occurs.
            target (str/Module/Package): the target node.
            what (str): what is imported (optional).
        """
        self.source = source
        self.lineno = lineno
        self.target = target
        self.what = what

    def __str__(self):
        what = f"{self.what or ''} from "
        target = self.target if self.external else self.target.absolute_name()
        return f"{self.source.name} imports {what}{target} (line {self.lineno})"

    @property
    def external(self) -> bool:
        """
        Property to tell if the dependency's target is a valid node.

        Returns:
            Whether the dependency's target is a valid node.
        """
        return isinstance(self.target, str)

__init__(source, lineno, target, what=None) ¤

Initialization method.

Parameters:

Name Type Description Default
source Module

source Module.

required
lineno int

number of line at which import statement occurs.

required
target str/Module/Package

the target node.

required
what str

what is imported (optional).

None
Source code in dependenpy/dsm.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def __init__(self, source, lineno, target, what=None):
    """
    Initialization method.

    Args:
        source (Module): source Module.
        lineno (int): number of line at which import statement occurs.
        target (str/Module/Package): the target node.
        what (str): what is imported (optional).
    """
    self.source = source
    self.lineno = lineno
    self.target = target
    self.what = what

external() property ¤

Property to tell if the dependency's target is a valid node.

Returns:

Type Description
bool

Whether the dependency's target is a valid node.

Source code in dependenpy/dsm.py
446
447
448
449
450
451
452
453
454
@property
def external(self) -> bool:
    """
    Property to tell if the dependency's target is a valid node.

    Returns:
        Whether the dependency's target is a valid node.
    """
    return isinstance(self.target, str)

Module ¤

Bases: LeafNode, NodeMixin, PrintMixin

Module class.

This class represents a Python module (a Python file).

Source code in dependenpy/dsm.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
class Module(LeafNode, NodeMixin, PrintMixin):  # noqa: WPS338
    """
    Module class.

    This class represents a Python module (a Python file).
    """

    RECURSIVE_NODES = (ast.ClassDef, ast.FunctionDef, ast.If, ast.IfExp, ast.Try, ast.With, ast.ExceptHandler)

    def __init__(self, name, path, dsm=None, package=None):
        """
        Initialization method.

        Args:
            name (str): name of the module.
            path (str): path to the module.
            dsm (DSM): parent DSM.
            package (Package): parent Package.
        """
        super().__init__()
        self.name = name
        self.path = path
        self.package = package
        self.dsm = dsm
        self.dependencies = []

    def __contains__(self, item) -> bool:
        """
        Whether given item is contained inside this module.

        Args:
            item (Package/Module): a package or module.

        Returns:
            True if self is item or item is self's package and
                self if an `__init__` module.
        """
        if self is item:
            return True
        elif self.package is item and self.name == "__init__":
            return True
        return False

    @property
    def ismodule(self) -> bool:
        """
        Inherited from NodeMixin. Always True.

        Returns:
            Whether this object is a module.
        """
        return True

    def as_dict(self, absolute: bool = False) -> dict:
        """
        Return the dependencies as a dictionary.

        Arguments:
            absolute: Whether to use the absolute name.

        Returns:
            dict: dictionary of dependencies.
        """
        return {
            "name": self.absolute_name() if absolute else self.name,
            "path": self.path,
            "dependencies": [
                {
                    # 'source': d.source.absolute_name(),  # redundant
                    "target": dep.target if dep.external else dep.target.absolute_name(),
                    "lineno": dep.lineno,
                    "what": dep.what,
                    "external": dep.external,
                }
                for dep in self.dependencies
            ],
        }

    def _to_text(self, **kwargs):
        indent = kwargs.pop("indent", 2)
        base_indent = kwargs.pop("base_indent", None)
        if base_indent is None:
            base_indent = indent
            indent = 0
        text = [" " * indent + self.name + "\n"]
        new_indent = indent + base_indent
        for dep in self.dependencies:
            external = "! " if dep.external else ""
            text.append(" " * new_indent + external + str(dep) + "\n")
        return "".join(text)

    def _to_csv(self, **kwargs):
        header = kwargs.pop("header", True)
        text = ["module,path,target,lineno,what,external\n" if header else ""]
        name = self.absolute_name()
        for dep in self.dependencies:
            target = dep.target if dep.external else dep.target.absolute_name()
            text.append(f"{name},{self.path},{target},{dep.lineno},{dep.what or ''},{dep.external}\n")
        return "".join(text)

    def _to_json(self, **kwargs):
        absolute = kwargs.pop("absolute", False)
        return json.dumps(self.as_dict(absolute=absolute), **kwargs)

    def build_dependencies(self):
        """
        Build the dependencies for this module.

        Parse the code with ast, find all the import statements, convert
        them into Dependency objects.
        """
        highest = self.dsm or self.root
        if self is highest:
            highest = LeafNode()
        for import_ in self.parse_code():
            target = highest.get_target(import_["target"])
            if target:
                what = import_["target"].split(".")[-1]
                if what != target.name:
                    import_["what"] = what
                import_["target"] = target
            self.dependencies.append(Dependency(source=self, **import_))

    def parse_code(self) -> list[dict]:
        """
        Read the source code and return all the import statements.

        Returns:
            list of dict: the import statements.
        """
        code = Path(self.path).read_text(encoding="utf-8")
        try:
            body = ast.parse(code).body
        except SyntaxError:
            code = code.encode("utf-8")  # type: ignore[assignment]
            try:  # noqa: WPS505
                body = ast.parse(code).body
            except SyntaxError:
                return []
        return self.get_imports(body)

    def get_imports(self, ast_body) -> list[dict]:  # noqa: WPS231,WPS615
        """
        Return all the import statements given an AST body (AST nodes).

        Args:
            ast_body (compiled code's body): the body to filter.

        Returns:
            The import statements.
        """
        imports: list[dict] = []
        for node in ast_body:
            if isinstance(node, ast.Import):
                imports.extend({"target": name.name, "lineno": node.lineno} for name in node.names)
            elif isinstance(node, ast.ImportFrom):
                for name in node.names:
                    abs_name = self.absolute_name(self.depth - node.level) + "." if node.level > 0 else ""
                    node_module = node.module + "." if node.module else ""
                    name = abs_name + node_module + name.name  # type: ignore[assignment]
                    imports.append({"target": name, "lineno": node.lineno})
            elif isinstance(node, Module.RECURSIVE_NODES):
                imports.extend(self.get_imports(node.body))
                if isinstance(node, ast.Try):
                    imports.extend(self.get_imports(node.finalbody))
        return imports

    def cardinal(self, to) -> int:
        """
        Return the number of dependencies of this module to the given node.

        Args:
            to (Package/Module): the target node.

        Returns:
            Number of dependencies.
        """
        return len([dep for dep in self.dependencies if not dep.external and dep.target in to])

__contains__(item) ¤

Whether given item is contained inside this module.

Parameters:

Name Type Description Default
item Package/Module

a package or module.

required

Returns:

Type Description
bool

True if self is item or item is self's package and self if an __init__ module.

Source code in dependenpy/dsm.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
def __contains__(self, item) -> bool:
    """
    Whether given item is contained inside this module.

    Args:
        item (Package/Module): a package or module.

    Returns:
        True if self is item or item is self's package and
            self if an `__init__` module.
    """
    if self is item:
        return True
    elif self.package is item and self.name == "__init__":
        return True
    return False

__init__(name, path, dsm=None, package=None) ¤

Initialization method.

Parameters:

Name Type Description Default
name str

name of the module.

required
path str

path to the module.

required
dsm DSM

parent DSM.

None
package Package

parent Package.

None
Source code in dependenpy/dsm.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def __init__(self, name, path, dsm=None, package=None):
    """
    Initialization method.

    Args:
        name (str): name of the module.
        path (str): path to the module.
        dsm (DSM): parent DSM.
        package (Package): parent Package.
    """
    super().__init__()
    self.name = name
    self.path = path
    self.package = package
    self.dsm = dsm
    self.dependencies = []

as_dict(absolute=False) ¤

Return the dependencies as a dictionary.

Parameters:

Name Type Description Default
absolute bool

Whether to use the absolute name.

False

Returns:

Name Type Description
dict dict

dictionary of dependencies.

Source code in dependenpy/dsm.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def as_dict(self, absolute: bool = False) -> dict:
    """
    Return the dependencies as a dictionary.

    Arguments:
        absolute: Whether to use the absolute name.

    Returns:
        dict: dictionary of dependencies.
    """
    return {
        "name": self.absolute_name() if absolute else self.name,
        "path": self.path,
        "dependencies": [
            {
                # 'source': d.source.absolute_name(),  # redundant
                "target": dep.target if dep.external else dep.target.absolute_name(),
                "lineno": dep.lineno,
                "what": dep.what,
                "external": dep.external,
            }
            for dep in self.dependencies
        ],
    }

build_dependencies() ¤

Build the dependencies for this module.

Parse the code with ast, find all the import statements, convert them into Dependency objects.

Source code in dependenpy/dsm.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def build_dependencies(self):
    """
    Build the dependencies for this module.

    Parse the code with ast, find all the import statements, convert
    them into Dependency objects.
    """
    highest = self.dsm or self.root
    if self is highest:
        highest = LeafNode()
    for import_ in self.parse_code():
        target = highest.get_target(import_["target"])
        if target:
            what = import_["target"].split(".")[-1]
            if what != target.name:
                import_["what"] = what
            import_["target"] = target
        self.dependencies.append(Dependency(source=self, **import_))

cardinal(to) ¤

Return the number of dependencies of this module to the given node.

Parameters:

Name Type Description Default
to Package/Module

the target node.

required

Returns:

Type Description
int

Number of dependencies.

Source code in dependenpy/dsm.py
406
407
408
409
410
411
412
413
414
415
416
def cardinal(self, to) -> int:
    """
    Return the number of dependencies of this module to the given node.

    Args:
        to (Package/Module): the target node.

    Returns:
        Number of dependencies.
    """
    return len([dep for dep in self.dependencies if not dep.external and dep.target in to])

get_imports(ast_body) ¤

Return all the import statements given an AST body (AST nodes).

Parameters:

Name Type Description Default
ast_body compiled code's body

the body to filter.

required

Returns:

Type Description
list[dict]

The import statements.

Source code in dependenpy/dsm.py
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def get_imports(self, ast_body) -> list[dict]:  # noqa: WPS231,WPS615
    """
    Return all the import statements given an AST body (AST nodes).

    Args:
        ast_body (compiled code's body): the body to filter.

    Returns:
        The import statements.
    """
    imports: list[dict] = []
    for node in ast_body:
        if isinstance(node, ast.Import):
            imports.extend({"target": name.name, "lineno": node.lineno} for name in node.names)
        elif isinstance(node, ast.ImportFrom):
            for name in node.names:
                abs_name = self.absolute_name(self.depth - node.level) + "." if node.level > 0 else ""
                node_module = node.module + "." if node.module else ""
                name = abs_name + node_module + name.name  # type: ignore[assignment]
                imports.append({"target": name, "lineno": node.lineno})
        elif isinstance(node, Module.RECURSIVE_NODES):
            imports.extend(self.get_imports(node.body))
            if isinstance(node, ast.Try):
                imports.extend(self.get_imports(node.finalbody))
    return imports

ismodule() property ¤

Inherited from NodeMixin. Always True.

Returns:

Type Description
bool

Whether this object is a module.

Source code in dependenpy/dsm.py
282
283
284
285
286
287
288
289
290
@property
def ismodule(self) -> bool:
    """
    Inherited from NodeMixin. Always True.

    Returns:
        Whether this object is a module.
    """
    return True

parse_code() ¤

Read the source code and return all the import statements.

Returns:

Type Description
list[dict]

list of dict: the import statements.

Source code in dependenpy/dsm.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def parse_code(self) -> list[dict]:
    """
    Read the source code and return all the import statements.

    Returns:
        list of dict: the import statements.
    """
    code = Path(self.path).read_text(encoding="utf-8")
    try:
        body = ast.parse(code).body
    except SyntaxError:
        code = code.encode("utf-8")  # type: ignore[assignment]
        try:  # noqa: WPS505
            body = ast.parse(code).body
        except SyntaxError:
            return []
    return self.get_imports(body)

Package ¤

Bases: RootNode, LeafNode, NodeMixin, PrintMixin

Package class.

This class represent Python packages as nodes in a tree.

Source code in dependenpy/dsm.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
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
228
229
230
231
232
233
234
235
236
class Package(RootNode, LeafNode, NodeMixin, PrintMixin):  # noqa: WPS215
    """
    Package class.

    This class represent Python packages as nodes in a tree.
    """

    def __init__(
        self,
        name: str,
        path: str,
        dsm: DSM = None,
        package: "Package" = None,
        limit_to: List[str] = None,
        build_tree: bool = True,
        build_dependencies: bool = True,
        enforce_init: bool = True,
    ):
        """
        Initialization method.

        Args:
            name: name of the package.
            path: path to the package.
            dsm: parent DSM.
            package: parent package.
            limit_to: list of string to limit the recursive tree-building to what is specified.
            build_tree: auto-build the tree or not.
            build_dependencies: auto-build the dependencies or not.
            enforce_init: if True, only treat directories if they contain an `__init__.py` file.
        """
        self.name = name
        self.path = path
        self.package = package
        self.dsm = dsm
        self.limit_to = limit_to or []
        self.enforce_init = enforce_init

        RootNode.__init__(self, build_tree)  # noqa: WPS609
        LeafNode.__init__(self)  # noqa: WPS609

        if build_tree and build_dependencies:
            self.build_dependencies()

    @property
    def ispackage(self) -> bool:
        """
        Inherited from NodeMixin. Always True.

        Returns:
            Whether this object is a package.
        """
        return True

    @property
    def issubpackage(self) -> bool:
        """
        Property to tell if this node is a sub-package.

        Returns:
            This package has a parent.
        """
        return self.package is not None

    @property
    def isroot(self) -> bool:
        """
        Property to tell if this node is a root node.

        Returns:
            This package has no parent.
        """
        return self.package is None

    def split_limits_heads(self) -> tuple[list[str], list[str]]:
        """
        Return first parts of dot-separated strings, and rest of strings.

        Returns:
            The heads and rest of the strings.
        """
        heads = []
        new_limit_to = []
        for limit in self.limit_to:
            if "." in limit:
                name, limit = limit.split(".", 1)  # noqa: WPS440
                heads.append(name)
                new_limit_to.append(limit)
            else:
                heads.append(limit)
        return heads, new_limit_to

    def build_tree(self):  # noqa: WPS231
        """Build the tree for this package."""
        for module in listdir(self.path):
            abs_m = join(self.path, module)
            if isfile(abs_m) and module.endswith(".py"):
                name = splitext(module)[0]
                if not self.limit_to or name in self.limit_to:
                    self.modules.append(Module(name, abs_m, self.dsm, self))
            elif isdir(abs_m):
                if isfile(join(abs_m, "__init__.py")) or not self.enforce_init:
                    heads, new_limit_to = self.split_limits_heads()
                    if not heads or module in heads:
                        self.packages.append(
                            Package(
                                module,
                                abs_m,
                                self.dsm,
                                self,
                                new_limit_to,
                                build_tree=True,
                                build_dependencies=False,
                                enforce_init=self.enforce_init,
                            )
                        )

    def cardinal(self, to) -> int:
        """
        Return the number of dependencies of this package to the given node.

        Args:
            to (Package/Module): target node.

        Returns:
            Number of dependencies.
        """
        return sum(module.cardinal(to) for module in self.submodules)

__init__(name, path, dsm=None, package=None, limit_to=None, build_tree=True, build_dependencies=True, enforce_init=True) ¤

Initialization method.

Parameters:

Name Type Description Default
name str

name of the package.

required
path str

path to the package.

required
dsm DSM

parent DSM.

None
package 'Package'

parent package.

None
limit_to List[str]

list of string to limit the recursive tree-building to what is specified.

None
build_tree bool

auto-build the tree or not.

True
build_dependencies bool

auto-build the dependencies or not.

True
enforce_init bool

if True, only treat directories if they contain an __init__.py file.

True
Source code in dependenpy/dsm.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def __init__(
    self,
    name: str,
    path: str,
    dsm: DSM = None,
    package: "Package" = None,
    limit_to: List[str] = None,
    build_tree: bool = True,
    build_dependencies: bool = True,
    enforce_init: bool = True,
):
    """
    Initialization method.

    Args:
        name: name of the package.
        path: path to the package.
        dsm: parent DSM.
        package: parent package.
        limit_to: list of string to limit the recursive tree-building to what is specified.
        build_tree: auto-build the tree or not.
        build_dependencies: auto-build the dependencies or not.
        enforce_init: if True, only treat directories if they contain an `__init__.py` file.
    """
    self.name = name
    self.path = path
    self.package = package
    self.dsm = dsm
    self.limit_to = limit_to or []
    self.enforce_init = enforce_init

    RootNode.__init__(self, build_tree)  # noqa: WPS609
    LeafNode.__init__(self)  # noqa: WPS609

    if build_tree and build_dependencies:
        self.build_dependencies()

build_tree() ¤

Build the tree for this package.

Source code in dependenpy/dsm.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def build_tree(self):  # noqa: WPS231
    """Build the tree for this package."""
    for module in listdir(self.path):
        abs_m = join(self.path, module)
        if isfile(abs_m) and module.endswith(".py"):
            name = splitext(module)[0]
            if not self.limit_to or name in self.limit_to:
                self.modules.append(Module(name, abs_m, self.dsm, self))
        elif isdir(abs_m):
            if isfile(join(abs_m, "__init__.py")) or not self.enforce_init:
                heads, new_limit_to = self.split_limits_heads()
                if not heads or module in heads:
                    self.packages.append(
                        Package(
                            module,
                            abs_m,
                            self.dsm,
                            self,
                            new_limit_to,
                            build_tree=True,
                            build_dependencies=False,
                            enforce_init=self.enforce_init,
                        )
                    )

cardinal(to) ¤

Return the number of dependencies of this package to the given node.

Parameters:

Name Type Description Default
to Package/Module

target node.

required

Returns:

Type Description
int

Number of dependencies.

Source code in dependenpy/dsm.py
226
227
228
229
230
231
232
233
234
235
236
def cardinal(self, to) -> int:
    """
    Return the number of dependencies of this package to the given node.

    Args:
        to (Package/Module): target node.

    Returns:
        Number of dependencies.
    """
    return sum(module.cardinal(to) for module in self.submodules)

ispackage() property ¤

Inherited from NodeMixin. Always True.

Returns:

Type Description
bool

Whether this object is a package.

Source code in dependenpy/dsm.py
153
154
155
156
157
158
159
160
161
@property
def ispackage(self) -> bool:
    """
    Inherited from NodeMixin. Always True.

    Returns:
        Whether this object is a package.
    """
    return True

isroot() property ¤

Property to tell if this node is a root node.

Returns:

Type Description
bool

This package has no parent.

Source code in dependenpy/dsm.py
173
174
175
176
177
178
179
180
181
@property
def isroot(self) -> bool:
    """
    Property to tell if this node is a root node.

    Returns:
        This package has no parent.
    """
    return self.package is None

issubpackage() property ¤

Property to tell if this node is a sub-package.

Returns:

Type Description
bool

This package has a parent.

Source code in dependenpy/dsm.py
163
164
165
166
167
168
169
170
171
@property
def issubpackage(self) -> bool:
    """
    Property to tell if this node is a sub-package.

    Returns:
        This package has a parent.
    """
    return self.package is not None

split_limits_heads() ¤

Return first parts of dot-separated strings, and rest of strings.

Returns:

Type Description
tuple[list[str], list[str]]

The heads and rest of the strings.

Source code in dependenpy/dsm.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def split_limits_heads(self) -> tuple[list[str], list[str]]:
    """
    Return first parts of dot-separated strings, and rest of strings.

    Returns:
        The heads and rest of the strings.
    """
    heads = []
    new_limit_to = []
    for limit in self.limit_to:
        if "." in limit:
            name, limit = limit.split(".", 1)  # noqa: WPS440
            heads.append(name)
            new_limit_to.append(limit)
        else:
            heads.append(limit)
    return heads, new_limit_to