Skip to content

sob.utilities

get_property_name

get_property_name(name: str) -> str

Converts a "camelCased" attribute/property name, a name which conflicts with a python keyword, or an otherwise non-compatible string to a PEP-8 compliant property name.

Examples:

>>> print(get_property_name("theBirdsAndTheBees"))
the_birds_and_the_bees

>>> print(get_property_name("theBirdsAndTheBEEs"))
the_birds_and_the_bees

>>> print(get_property_name("theBirdsAndTheBEEsEs"))
the_birds_and_the_be_es_es

>>> print(get_property_name("FYIThisIsAnAcronym"))
fyi_this_is_an_acronym

>>> print(get_property_name("in"))
in_

>>> print(get_property_name("id"))
id_

>>> print(get_property_name("one2one"))  # No change needed
one2one

>>> print(get_property_name("One2One"))
one_2_one

>>> print(get_property_name("@One2One"))
one_2_one

>>> print(get_property_name("One2One-ALL"))
one_2_one_all

>>> print(get_property_name("one2one-ALL"))
one2one_all

>>> print(get_property_name("type"))
type_

>>> print(get_property_name("@type"))
type_
Source code in src/sob/utilities.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
 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
107
108
109
110
111
112
113
114
115
def get_property_name(name: str) -> str:
    """
    Converts a "camelCased" attribute/property name, a name which conflicts
    with a python keyword, or an otherwise non-compatible string to a PEP-8
    compliant property name.

    Examples:

        >>> print(get_property_name("theBirdsAndTheBees"))
        the_birds_and_the_bees

        >>> print(get_property_name("theBirdsAndTheBEEs"))
        the_birds_and_the_bees

        >>> print(get_property_name("theBirdsAndTheBEEsEs"))
        the_birds_and_the_be_es_es

        >>> print(get_property_name("FYIThisIsAnAcronym"))
        fyi_this_is_an_acronym

        >>> print(get_property_name("in"))
        in_

        >>> print(get_property_name("id"))
        id_

        >>> print(get_property_name("one2one"))  # No change needed
        one2one

        >>> print(get_property_name("One2One"))
        one_2_one

        >>> print(get_property_name("@One2One"))
        one_2_one

        >>> print(get_property_name("One2One-ALL"))
        one_2_one_all

        >>> print(get_property_name("one2one-ALL"))
        one2one_all

        >>> print(get_property_name("type"))
        type_

        >>> print(get_property_name("@type"))
        type_
    """
    # Replace accented and otherwise modified latin characters with their
    # basic latin equivalent
    name = normalize("NFKD", name)
    # Replace any remaining non-latin characters with underscores
    name = re.sub(r"([^\x20-\x7F]|\s)+", "_", name)
    # Only insert underscores between letters and numbers if camelCasing is
    # found in the original string
    if re.search(r"[A-Z][a-z]", name) or re.search(r"[a-z][A-Z]", name):
        name = re.sub(r"([0-9])([a-zA-Z])", r"\1_\2", name)
        name = re.sub(r"([a-zA-Z])([0-9])", r"\1_\2", name)
    # Insert underscores between lowercase and uppercase characters
    name = re.sub(r"([a-z])([A-Z])", r"\1_\2", name)
    # Insert underscores between uppercase characters and following uppercase
    # characters which are followed by lowercase characters (indicating the
    # latter uppercase character was intended as part of a capitalized word),
    # except where the trailing lowercase character is a solo lowercase "s"
    # (pluralizing the acronym).
    name = re.sub(r"([A-Z])([A-Z])([a-rt-z]|s(?!\b))", r"\1_\2\3", name)
    # Replace any series of one or more non-alphanumeric characters remaining
    # with a single underscore
    name = re.sub(r"[^\w_]+", "_", name).lower()
    # Replace any two or more adjacent underscores with a single underscore
    name = re.sub(r"__+", "_", name).lstrip("_")
    # Append an underscore to the keyword until it does not conflict with any
    # python keywords, built-ins, or potential module imports
    while (
        iskeyword(name)
        or (name in builtins.__dict__)
        or (name in {"self", "decimal", "datetime", "typing", "type"})
    ):
        name = f"{name}_"
    return name

get_class_name

get_class_name(name: str) -> str

This function accepts a string and returns a variation of that string which is a PEP-8 compatible python class name.

Examples:

>>> print(get_class_name("the birds and the bees"))
TheBirdsAndTheBees

>>> print(get_class_name("the-birds-and-the-bees"))
TheBirdsAndTheBees

>>> print(get_class_name("**the - birds - and - the - bees**"))
TheBirdsAndTheBees

>>> print(get_class_name("FYI is an acronym"))
FYIIsAnAcronym

>>> print(get_class_name("in-you-go"))
InYouGo

>>> print(get_class_name("False"))
False_

>>> print(get_class_name("True"))
True_

>>> print(get_class_name("ABC Acronym"))
ABCAcronym

>>> print(get_class_name("AB CD Efg"))
ABCdEfg
Source code in src/sob/utilities.py
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
def get_class_name(name: str) -> str:
    """
    This function accepts a string and returns a variation of that string
    which is a PEP-8 compatible python class name.

    Examples:

        >>> print(get_class_name("the birds and the bees"))
        TheBirdsAndTheBees

        >>> print(get_class_name("the-birds-and-the-bees"))
        TheBirdsAndTheBees

        >>> print(get_class_name("**the - birds - and - the - bees**"))
        TheBirdsAndTheBees

        >>> print(get_class_name("FYI is an acronym"))
        FYIIsAnAcronym

        >>> print(get_class_name("in-you-go"))
        InYouGo

        >>> print(get_class_name("False"))
        False_

        >>> print(get_class_name("True"))
        True_

        >>> print(get_class_name("ABC Acronym"))
        ABCAcronym

        >>> print(get_class_name("AB CD Efg"))
        ABCdEfg
    """
    name = camel(name, capitalize=True)
    while iskeyword(name) or (name in builtins.__dict__):
        name = f"{name}_"
    if name.startswith(_DIGITS_TUPLE):
        name = f"_{name}"
    return name

camel

camel(string: str, *, capitalize: bool = False) -> str

This function returns a camelCased representation of the input string.

Parameters:

  • string (str) –

    The string to be camelCased.

  • capitalize (bool, default: False ) –

    If this is true, the first letter will be capitalized.

Examples:

>>> print(camel("the birds and the bees"))
theBirdsAndTheBees

>>> print(camel("the birds and the bees", capitalize=True))
TheBirdsAndTheBees

>>> print(camel("the-birds-and-the-bees"))
theBirdsAndTheBees

>>> print(camel("**the - birds - and - the - bees**"))
theBirdsAndTheBees

>>> print(camel("FYI is an acronym"))
FYIIsAnAcronym

>>> print(camel("in-you-go"))
inYouGo

>>> print(camel("False"))
false

>>> print(camel("True"))
true

>>> print(camel("in"))
in

>>> print(camel("AB CD Efg", capitalize=True))
ABCdEfg

>>> print(camel("ABC DEF GHI", capitalize=True))
AbcDefGhi

>>> print(camel("ABC_DEF_GHI", capitalize=True))
AbcDefGhi

>>> print(camel("ABC DEF GHI"))
abcDefGhi

>>> print(camel("ABC_DEF_GHI"))
abcDefGhi

>>> print(camel("AB_CDEfg"))
ABCdEfg
Source code in src/sob/utilities.py
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
237
238
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
def camel(string: str, *, capitalize: bool = False) -> str:
    """
    This function returns a camelCased representation of the input string.

    Parameters:
        string: The string to be camelCased.
        capitalize: If this is `true`, the first letter will be capitalized.

    Examples:

        >>> print(camel("the birds and the bees"))
        theBirdsAndTheBees

        >>> print(camel("the birds and the bees", capitalize=True))
        TheBirdsAndTheBees

        >>> print(camel("the-birds-and-the-bees"))
        theBirdsAndTheBees

        >>> print(camel("**the - birds - and - the - bees**"))
        theBirdsAndTheBees

        >>> print(camel("FYI is an acronym"))
        FYIIsAnAcronym

        >>> print(camel("in-you-go"))
        inYouGo

        >>> print(camel("False"))
        false

        >>> print(camel("True"))
        true

        >>> print(camel("in"))
        in

        >>> print(camel("AB CD Efg", capitalize=True))
        ABCdEfg

        >>> print(camel("ABC DEF GHI", capitalize=True))
        AbcDefGhi

        >>> print(camel("ABC_DEF_GHI", capitalize=True))
        AbcDefGhi

        >>> print(camel("ABC DEF GHI"))
        abcDefGhi

        >>> print(camel("ABC_DEF_GHI"))
        abcDefGhi

        >>> print(camel("AB_CDEfg"))
        ABCdEfg
    """
    index: int
    character: str
    string = normalize("NFKD", string)
    characters: list[str] = []
    all_uppercase: bool = string.upper() == string
    capitalize_next: bool = capitalize
    uncapitalize_next: bool = (not capitalize) and (
        len(string) < 2  # noqa: PLR2004
        or all_uppercase
        or not (
            string[0] in _UPPERCASE_ALPHABET
            and string[1] in _UPPERCASE_ALPHABET
        )
    )
    for index, character in enumerate(string):
        if character in _ALPHANUMERIC_CHARACTERS:
            if capitalize_next:
                if all_uppercase:
                    uncapitalize_next = True
                elif capitalize or characters:
                    # This prevents two acronyms which are adjacent from
                    # retaining capitalization (since word separations would
                    # not be possible to identify if caps were kept for both)
                    if characters and (characters[-1] in _UPPERCASE_ALPHABET):
                        uncapitalize_next = True
                    character = character.upper()  # noqa: PLW2901
            elif uncapitalize_next and character:
                if character in _LOWERCASE_ALPHABET:
                    uncapitalize_next = False
                else:
                    character = character.lower()  # noqa: PLW2901
                    # Halt lowercasing if the next character starts a
                    # camelCased word
                    next_index: int = index + 1
                    tail: str = string[next_index:]
                    if (
                        len(tail) > 1
                        and tail[0] in _UPPERCASE_ALPHABET
                        and tail[1] in _LOWERCASE_ALPHABET
                    ):
                        uncapitalize_next = False
            characters.append(character)
            capitalize_next = False
        else:
            capitalize_next = True
            uncapitalize_next = False
    return "".join(characters)

camel_split

camel_split(string: str) -> tuple[str, ...]

Split a string of camelCased words into a tuple.

Examples:

>>> camel_split("theBirdsAndTheBees")
('the', 'Birds', 'And', 'The', 'Bees')

>>> camel_split("theBirdsAndTheBees123")
('the', 'Birds', 'And', 'The', 'Bees', '123')

>>> camel_split("theBirdsAndTheBeesABC123")
('the', 'Birds', 'And', 'The', 'Bees', 'ABC', '123')

>>> camel_split("the-Birds-&-The-Bs-ABC--123")
('the', '-', 'Birds', '-&-', 'The', '-', 'Bs', '-', 'ABC', '--', '123')

>>> camel_split("THEBirdsAndTheBees")
('THE', 'Birds', 'And', 'The', 'Bees')
Source code in src/sob/utilities.py
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
def camel_split(string: str) -> tuple[str, ...]:
    """
    Split a string of camelCased words into a tuple.

    Examples:

        >>> camel_split("theBirdsAndTheBees")
        ('the', 'Birds', 'And', 'The', 'Bees')

        >>> camel_split("theBirdsAndTheBees123")
        ('the', 'Birds', 'And', 'The', 'Bees', '123')

        >>> camel_split("theBirdsAndTheBeesABC123")
        ('the', 'Birds', 'And', 'The', 'Bees', 'ABC', '123')

        >>> camel_split("the-Birds-&-The-Bs-ABC--123")
        ('the', '-', 'Birds', '-&-', 'The', '-', 'Bs', '-', 'ABC', '--', '123')

        >>> camel_split("THEBirdsAndTheBees")
        ('THE', 'Birds', 'And', 'The', 'Bees')
    """
    words: list[list[str]] = []
    preceding_character_type: _CharacterType | None = None
    for character in string:
        character_type: _CharacterType = (
            _CharacterType.LOWERCASE
            if character in _LOWERCASE_ALPHABET
            else (
                _CharacterType.DIGIT
                if character in _DIGITS
                else (
                    _CharacterType.UPPERCASE
                    if character in _UPPERCASE_ALPHABET
                    else _CharacterType.OTHER
                )
            )
        )
        if character_type == _CharacterType.LOWERCASE:
            if preceding_character_type == _CharacterType.LOWERCASE:
                # If following another lowercase character, a lowercase
                # character always continues that word
                words[-1].append(character)
            elif preceding_character_type == _CharacterType.UPPERCASE:
                if len(words[-1]) > 1:
                    # When following a multi-character uppercase word,
                    # the preceding word's last character should be removed
                    # and a new word created from that preceding character
                    # as well as the current lowercase character (until
                    # followed by a lowercase character, the preceding
                    # uppercase character was inferred to be part of an,
                    # however now we know it was either following an acronym,
                    # or following a single-character word)
                    words.append([words[-1].pop(), character])
                else:
                    # When following an uppercase character, a lowercase
                    # character should be added to the preceding word if that
                    # word has only one character thus far
                    words[-1].append(character)
            else:
                words.append([character])
            preceding_character_type = _CharacterType.LOWERCASE
        else:
            # Any type of character besides one from the *lowercase alphabet*
            # should start a new word if it follows a character of a
            # different type
            if preceding_character_type == character_type:
                words[-1].append(character)
            else:
                words.append([character])
            preceding_character_type = character_type
    return tuple("".join(word) for word in words)

indent

indent(
    string: str,
    number_of_spaces: int = 4,
    start: int = 1,
    stop: int | None = None,
) -> str

Indent text by number_of_spaces starting at line index start and stopping at line index stop.

Source code in src/sob/utilities.py
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
def indent(
    string: str,
    number_of_spaces: int = 4,
    start: int = 1,
    stop: int | None = None,
) -> str:
    """
    Indent text by `number_of_spaces` starting at line index `start` and
    stopping at line index `stop`.
    """
    indented_text = string
    if ("\n" in string) or start == 0:
        lines: list[str] = string.split("\n")
        if stop:
            if stop < 0:
                stop = len(lines) - stop
        else:
            stop = len(lines)
        index: int
        for index in range(start, stop):
            line: str = lines[index]
            line_indent: str = " " * number_of_spaces
            lines[index] = f"{line_indent}{line}".rstrip()
        indented_text = "\n".join(lines)
    return indented_text

get_url_relative_to

get_url_relative_to(
    absolute_url: str, base_url: str
) -> str

Returns a relative URL given an absolute URL and a base URL

Source code in src/sob/utilities.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def get_url_relative_to(absolute_url: str, base_url: str) -> str:
    """
    Returns a relative URL given an absolute URL and a base URL
    """
    # If no portion of the absolute URL is shared with the base URL--the
    # absolute URL will be returned
    relative_url: str = absolute_url
    base_url = _url_directory_and_file_name(base_url)[0]
    if base_url:
        relative_url = ""
        # URLs are not case-sensitive
        base_url = base_url.lower()
        lowercase_absolute_url = absolute_url.lower()
        while base_url and (
            base_url.lower() != lowercase_absolute_url[: len(base_url)]
        ):
            relative_url = "../" + relative_url
            base_url = _url_directory_and_file_name(base_url[:-1])[0]
        base_url_length: int = len(base_url)
        relative_url += absolute_url[base_url_length:]
    return relative_url

split_long_docstring_lines

split_long_docstring_lines(
    docstring: str,
    max_line_length: int = sob.utilities.MAX_LINE_LENGTH,
) -> str

Split long docstring lines.

Example:

>>> print(
...     split_long_docstring_lines(
...         "    Lorem ipsum dolor sit amet, consectetur adipiscing "
...         "elit. Nullam faucibu odio a urna elementum, eu tempor "
...         "nisl efficitur."
...     )
... )
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam faucibu
    odio a urna elementum, eu tempor nisl efficitur.
Source code in src/sob/utilities.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
def split_long_docstring_lines(
    docstring: str, max_line_length: int = MAX_LINE_LENGTH
) -> str:
    """
    Split long docstring lines.

    Example:

        >>> print(
        ...     split_long_docstring_lines(
        ...         "    Lorem ipsum dolor sit amet, consectetur adipiscing "
        ...         "elit. Nullam faucibu odio a urna elementum, eu tempor "
        ...         "nisl efficitur."
        ...     )
        ... )
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam faucibu
            odio a urna elementum, eu tempor nisl efficitur.
    """  # noqa: E501
    line: str
    indent_: str = "    "
    if "\t" in docstring:
        docstring = docstring.replace("\t", indent_)
    lines: list[str] = docstring.split("\n")
    indentation_length: int = sys.maxsize
    for line in filter(None, lines):
        matched = re.match(r"^[ ]+", line)
        if matched:
            indentation_length = min(indentation_length, len(matched.group()))
        else:
            indentation_length = 0
            break
    indent_ = " " * (indentation_length or 4)
    if indentation_length < sys.maxsize:
        docstring = "\n".join(
            _split_long_comment_line(
                indent_ + line[indentation_length:],
                max_line_length,
                prefix="",
            )
            for line in lines
        )
    # Strip trailing whitespace and empty lines
    return re.sub(r"[ ]+(\n|$)", r"\1", docstring)

suffix_long_lines

suffix_long_lines(
    text: str,
    max_line_length: int = sob.utilities.MAX_LINE_LENGTH,
    suffix: str = "  # noqa: E501",
) -> str

This function adds a suffix to the end of any line of code longer than max_line_length.

Parameters:

  • text (str) –

    Text representing python code

  • max_line_length (int, default: sob.utilities.MAX_LINE_LENGTH ) –

    The length at which a line should have the suffix appended. If this is a negative integer (or zero), the sum of this integer + MAX_LINE_LENGTH is used

  • suffix (str, default: ' # noqa: E501' ) –

    The default suffix indicates to linters that a long line should be permitted

Example:

>>> print(
...     suffix_long_lines(
...         "A short line...\n"
...         "Lorem ipsum dolor sit amet, consectetur adipiscing "
...         "elit. Nullam faucibu odio a urna elementum, eu tempor "
...         "nisl efficitur.\n"
...         "...another short line"
...     )
... )
A short line...
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam faucibu odio a urna elementum, eu tempor nisl efficitur.
...another short line
Source code in src/sob/utilities.py
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
def suffix_long_lines(
    text: str,
    max_line_length: int = MAX_LINE_LENGTH,
    suffix: str = "  # noqa: E501",
) -> str:
    """
    This function adds a suffix to the end of any line of code longer than
    `max_line_length`.

    Parameters:
        text: Text representing python code
        max_line_length:
            The length at which a line should have the `suffix` appended. If
            this is a *negative* integer (or zero), the sum of this integer +
            `MAX_LINE_LENGTH` is used
        suffix: The default suffix indicates to linters that
            a long line should be permitted

    Example:

        >>> print(
        ...     suffix_long_lines(
        ...         "A short line...\\n"
        ...         "Lorem ipsum dolor sit amet, consectetur adipiscing "
        ...         "elit. Nullam faucibu odio a urna elementum, eu tempor "
        ...         "nisl efficitur.\\n"
        ...         "...another short line"
        ...     )
        ... )
        A short line...
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam faucibu odio a urna elementum, eu tempor nisl efficitur.
        ...another short line

    """  # noqa: E501
    return "\n".join(
        _iter_suffix_long_lines(
            text, max_line_length=max_line_length, suffix=suffix
        )
    )

iter_properties_values

iter_properties_values(
    object_: object, *, include_private: bool = False
) -> collections.abc.Iterable[tuple[str, typing.Any]]

This function iterates over an object's public (non-callable) properties, yielding a tuple comprised of each attribute/property name and value.

Parameters:

  • object_ (object) –
  • include_private (bool, default: False ) –

    If this is True, private properties (those starting with an underscore) will be included in the iteration.

Source code in src/sob/utilities.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def iter_properties_values(
    object_: object, *, include_private: bool = False
) -> Iterable[tuple[str, Any]]:
    """
    This function iterates over an object's public (non-callable)
    properties, yielding a tuple comprised of each attribute/property name and
    value.

    Parameters:
        object_:
        include_private: If this is `True`, private properties (those
            starting with an underscore) will be included in the iteration.
    """
    names: Iterable[str] = dir(object_)
    if not include_private:
        names = filter(_is_public, names)

    def get_name_value(name: str) -> tuple[str, str] | None:
        value: Any = getattr(object_, name, lambda: None)
        if callable(value):
            return None
        return name, value

    return filter(None, map(get_name_value, names))

get_qualified_name

get_qualified_name(
    type_or_module: (
        type | typing.Callable | types.ModuleType
    ),
) -> str

This function return the fully qualified name for a type or module.

Examples:

>>> print(get_qualified_name(get_qualified_name))
sob.utilities.get_qualified_name

>>> from sob import model
>>> print(get_qualified_name(model.marshal))
sob.model.marshal
Source code in src/sob/utilities.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
def get_qualified_name(type_or_module: type | Callable | ModuleType) -> str:
    """
    This function return the fully qualified name for a type or module.

    Examples:

        >>> print(get_qualified_name(get_qualified_name))
        sob.utilities.get_qualified_name

        >>> from sob import model
        >>> print(get_qualified_name(model.marshal))
        sob.model.marshal
    """
    if not isinstance(type_or_module, QUALIFIED_NAME_ARGUMENT_TYPES):
        raise TypeError(type_or_module)
    type_name: str
    if isinstance(type_or_module, ModuleType):
        type_name = type_or_module.__name__
    else:
        type_name = getattr(
            type_or_module,
            "__qualname__",
            getattr(type_or_module, "__name__", ""),
        )
        if "<" in type_name:
            name_part: str
            type_name = ".".join(
                filter(
                    lambda name_part: not name_part.startswith("<"),
                    type_name.split("."),
                )
            )
        if (not type_name) and hasattr(type_or_module, "__origin__"):
            # If this is a generic alias, we can use `repr`
            # to get the qualified type name
            type_name = repr(type_or_module)
        if not type_name:
            msg = (
                "A qualified type name could not be inferred for "
                f"`{type_or_module!r}` "
                f"(an instance of {type(type_or_module).__name__})"
            )
            raise TypeError(msg)
        if type_or_module.__module__ not in (
            "builtins",
            "__builtin__",
            "__main__",
            "__init__",
        ):
            type_name = type_or_module.__module__ + "." + type_name
    return type_name

get_calling_module_name

get_calling_module_name(depth: int = 1) -> str

This function returns the name of the module from which the function which invokes this function was called.

Parameters:

  • depth (int, default: 1 ) –

    This defaults to 1, indicating we want to return the name of the module wherein get_calling_module_name is being called. If set to 2, it would instead indicate the module.

Examples:

>>> print(get_calling_module_name())
sob.utilities

>>> print(get_calling_module_name(2))
doctest
Source code in src/sob/utilities.py
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
def get_calling_module_name(depth: int = 1) -> str:
    """
    This function returns the name of the module from which the function
    which invokes this function was called.

    Parameters:
        depth: This defaults to `1`, indicating we want to return the name
            of the module wherein `get_calling_module_name` is being called.
            If set to `2`, it would instead indicate the module.

    Examples:

        >>> print(get_calling_module_name())
        sob.utilities

        >>> print(get_calling_module_name(2))
        doctest
    """
    name: str
    try:
        name = sys._getframe(  # noqa: SLF001
            depth
        ).f_globals.get("__name__", "__main__")
    except (AttributeError, ValueError):
        name = "__main__"
    return name

get_calling_function_qualified_name

get_calling_function_qualified_name(
    depth: int = 1,
) -> str | None

Return the fully qualified name of the function from within which this is being called

Examples:

>>> def my_function() -> str:
...     return get_calling_function_qualified_name()
>>> print(my_function())
sob.utilities.my_function

>>> class MyClass:
...     def __call__(self) -> None:
...         return self.my_method()
...
...     def my_method(self) -> str:
...         return get_calling_function_qualified_name()
>>> print(MyClass()())
sob.utilities.MyClass.my_method
Source code in src/sob/utilities.py
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
def get_calling_function_qualified_name(depth: int = 1) -> str | None:
    """
    Return the fully qualified name of the function from within which this is
    being called

    Examples:

        >>> def my_function() -> str:
        ...     return get_calling_function_qualified_name()
        >>> print(my_function())
        sob.utilities.my_function

        >>> class MyClass:
        ...     def __call__(self) -> None:
        ...         return self.my_method()
        ...
        ...     def my_method(self) -> str:
        ...         return get_calling_function_qualified_name()
        >>> print(MyClass()())
        sob.utilities.MyClass.my_method
    """
    if not isinstance(depth, int):
        raise TypeError(depth)
    try:
        stack_ = stack()
    except IndexError:
        return None
    if len(stack_) < (depth + 1):
        return None
    return ".".join(reversed(tuple(_iter_frame_info_names(stack_[depth]))))

get_source

get_source(
    object_: type | typing.Callable | types.ModuleType,
) -> str

Get the source code which defined an object.

Source code in src/sob/utilities.py
766
767
768
769
770
771
772
773
def get_source(object_: type | Callable | ModuleType) -> str:
    """
    Get the source code which defined an object.
    """
    object_source: str = getattr(object_, "_source", "")
    if not object_source:
        object_source = getsource(object_)
    return object_source

represent

represent(value: typing.Any) -> str

Returns a string representation of a value, formatted to minimize character width, and utilizing fully qualified class/function names (including module) where applicable.

Parameters:

  • value (typing.Any) –
Source code in src/sob/utilities.py
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
def represent(value: Any) -> str:
    """
    Returns a string representation of a value, formatted to minimize
    character width, and utilizing fully qualified class/function names
    (including module) where applicable.

    Parameters:
        value:
    """
    value_representation: str
    if isinstance(value, type):
        value_representation = get_qualified_name(value)
    else:
        value_type: type = type(value)
        if value_type is list:
            value_representation = _repr_list(value)
        elif value_type is tuple:
            value_representation = _repr_tuple(value)
        elif value_type is set:
            value_representation = _repr_set(value)
        elif value_type is dict:
            value_representation = _repr_dict(value)
        else:
            value_representation = repr(value)
            if (
                value_type is str
                and '"' not in value_representation
                and value_representation.startswith("'")
                and value_representation.endswith("'")
            ):
                value_representation = f'"{value_representation[1:-1]}"'
    return value_representation

get_method

get_method(
    object_instance: object,
    method_name: str,
    default: (
        typing.Callable | sob._types.Undefined | None
    ) = sob._types.UNDEFINED,
) -> typing.Callable[..., typing.Any] | None

This function attempts to retrieve an object's method, by name, if the method exists. If the object does not have a method with the given name, this function returns the defualt function (if provided), otherwise None.

Parameters:

  • object_instance (object) –
  • method_name (str) –
  • default (typing.Callable | sob._types.Undefined | None, default: sob._types.UNDEFINED ) –
Source code in src/sob/utilities.py
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
def get_method(
    object_instance: object,
    method_name: str,
    default: Callable | Undefined | None = UNDEFINED,
) -> Callable[..., Any] | None:
    """
    This function attempts to retrieve an object's method, by name, if the
    method exists. If the object does not have a method with the given name,
    this function returns the `defualt` function (if provided), otherwise
    `None`.

    Parameters:
        object_instance:
        method_name:
        default:
    """
    method: Callable
    try:
        method = getattr(object_instance, method_name)
    except AttributeError:
        if isinstance(default, Undefined):
            raise
        return default
    if callable(method):
        return method
    if isinstance(default, Undefined):
        message: str = (
            f"{get_qualified_name(type(object_instance))}.{method_name} "
            "is not callable."
        )
        raise AttributeError(message)  # noqa: TRY004
    return method