File: instance_processing.py

package info (click to toggle)
freeorion 0.5.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 194,920 kB
  • sloc: cpp: 186,821; python: 40,979; ansic: 1,164; xml: 721; makefile: 32; sh: 7
file content (54 lines) | stat: -rw-r--r-- 1,939 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
from collections.abc import Iterator
from logging import error, warning
from typing import Any

from stub_generator.interface_inspector.inspection_helpers import (
    _get_member_info,
    _getmembers,
)

_INVALID_CLASSES = {"method"}


class InstanceInfo:
    def __init__(self, class_name: str, attributes: dict[str, Any], parents: list[str], location: str):
        self.class_name = class_name
        self.attributes = attributes
        self.parents = parents
        self.location = location


def _inspect_instance(instance, location):
    parents = instance.__class__.mro()[1:-2]
    parent_attrs = sum((dir(parent) for parent in instance.__class__.mro()[1:]), [])

    attrs = {}

    for attr_name, member in _getmembers(instance):
        if attr_name not in parent_attrs + ["__module__"]:
            attrs[attr_name] = _get_member_info(f"{instance.__class__.__name__}.{attr_name}", member)
    return InstanceInfo(instance.__class__.__name__, attrs, [str(parent.__name__) for parent in parents], location)


def is_built_in(instance: Any) -> bool:
    """
    Return is instance is one of builtin type.

    Inherited classes from built in return False.
    """
    built_in_types = {str, float, int, tuple, tuple, list, dict, set}
    return type(instance) in built_in_types


def inspect_instances(instances) -> Iterator[InstanceInfo]:
    for location, instance in instances:
        if is_built_in(instance):
            warning("Argument at %s is builtin python instance: (%s) %s", location, type(instance), instance)
            continue
        if instance.__class__.__name__ in _INVALID_CLASSES:
            warning("Argument at %s is not allowed: (%s) %s", location, type(instance), instance)
            continue
        try:
            yield _inspect_instance(instance, location)
        except Exception as e:
            error("Error inspecting: '%s' with '%s': %s", type(instance), type(e), e, exc_info=True)