Repository navigation
Python
The rules of the method stereotypes, the free-function stereotypes, and the class stereotypes hold in Python as in every language of Stereocode. The section Data Members and Calls of the method stereotypes states the conventions by which Stereocode determines the facts of these rules in every language. Python code need not declare the data members of a class or the types of its variables. The section Language Facts therefore replaces or adds to these conventions for Python. This page also gives the built-in lists that Stereocode reads for Python and one labeled example of each stereotype.
- Every named class outside the bodies of functions is a type. Its parents are the positional entries of the list after its name, while a keyword entry such as
metaclass=Metais no parent. - Since every Python type is a class, the options of structs, interfaces, unions, and enums (
-t,-i,-u, and-e) select nothing in Python. - A function directly in the body of a class is a method, unless the decorator
@staticmethodor@classmethodmarks a static method or a class method.__init__and__new__get the stereotype constructor, while__del__gets destructor. Python has no copy constructor. - With
-f, the functions at the top level of a file, the static methods, and the class methods get the stereotypes of free functions. A free function namedmaingets main. The first parameter of a class method stands for the class. A name reached through this parameter, such ascls.count, is a global of the class. - A body is empty when it holds nothing but comments, a docstring,
pass, and.... - A class defined in a function is a local class and gets no stereotype.
- A method accesses its object through its first parameter, named
selfby convention. This parameter counts as no parameter in the rules. - Every name that a method reaches through the object, such as
self.total, is a data member of the class, unless the class or an ancestor in the archive defines a method or a class of that name. The body of a class declares further data members, namely its annotated names other than those ofClassVar, such astotal: int. - A name that the body of a class assigns outside its methods, such as
count = 0, is a global of the class. The code reaches such a global through the name of the class, whileself.countnames a data member, also where the body of the class assigns a default value to the name. - A property, which a decorator such as
@propertyor@<name>.settermarks, is a method with stereotypes of its own. For the other methods, the name of a property is a data member.self.areathus reads a data member whereareais a property. - Since srcML marks an f-string as one literal, Stereocode reads the names in its placeholders from the text.
f"{self.total}"thus reads the data membertotal.
- The type of a parameter, a local variable, a data member, or a returned value is the type that its annotation names. Without an annotation, a variable that the code assigns a newly created object has the class of that object. A data member assigned an annotated parameter has the type of that parameter. Any other type is unknown. An unknown type counts as primitive and thus makes no method a collaborator.
- The return annotation
Noneis void, whileboolis Boolean. - Every parameter other than the object shares its object with the caller, unless its annotation names a primitive type or the parameter gathers arguments, as
*argsand**kwargsdo. A write through a shared parameter changes an object of the caller, as does a call on the parameter unless its method is a query method. - A write through a member or an index of a parameter or a local variable, such as
p.x = 1orp[i] = 1, changes the object that the variable refers to. - A local variable is a name that the body assigns, such as the target of an assignment, of a
forloop, of awith ... as, of anexcept ... as, of a comprehension, or of the walrus operator. The scope of a local variable is the whole body of the function. A name that aglobalstatement of the function declares is the global of that name. - The parameters and the local variables of a nested function or a lambda are local variables of the enclosing function.
- A variable at the top level of a file is a global of the module of the file. A name without a qualifier refers only to the globals of its own file, while code in another file accesses a global through the name of the module, such as
settings.level. An imported name is no variable. - The globals of
__init__.pyare the globals of its package. Functions and classes are no variables. A call on a global changes the global unless its method is a query method, since Python has no constant globals. - A write to a variable of another class, such as
Other.count = 1, makes the method a collaborator, while a write to a variable of a module, such assettings.debug = True, does not.
- An expression is Boolean by its form when it is a Boolean literal, a negation, a comparison, a call of a built-in function that tests its argument, such as
isinstance, or a call of a method of a built-in type that tests its object, such asstartswith. A conjunction, a disjunction, or a conditional expression is Boolean by its form when each of its results is Boolean by its form. The value of any other call is not Boolean by its form, since the called function may return any value. - A
yieldwith a value counts as a return of that value, while ayieldin a nested function or a lambda returns no value of the enclosing function.return Nonecounts as areturnwithout a value. - A function without a return annotation returns
voidwhen noreturnand noyieldgives a value. Otherwise, such a function returns a Boolean when each returned expression is Boolean by its form and the class of an object when it returns an object that it creates. Any other such function returns an unknown type.
-
self.m()calls a method of the object, unlessmnames a data member of the class and no method of the class or of its ancestors has that name.self.on_fire()of a data member that stores a function is thus a call of a variable. A static method or a class method called through the object is a call of a free function. -
super().m()calls a method of a parent, as does a call under the name of the class or of a parent with the object as its first argument, such asBase.reset(self)ordict.__setitem__(self, key, value). The classobjectis a parent of every class. -
self.__repr__()andself.__eq__(other)read the object where no class of the archive defines the method, since these methods are accessors of the root classobject.self.get(key)in a subclass ofdictreads the object as well, sincegetis a query method anddictlies outside the archive. -
f(),module.f(), andcls.f()are calls of free functions, as isName.f()without the object as its first argument. - A call creates an object, as
newdoes in the other languages, when its name, alone or after the names of modules, is a class of the archive or follows the CapWords convention of class names without naming a free function of the archive.raise ValueError("x")thus holds a constructor call.cls(x)in a class method,type(x)(), andx.__class__()create objects as well. - A name called on the object creates an object only where the name is a class of the archive or a CapWords variable of the class, such as
self.RequestHandlerClass(). A name called on a data member, a local variable, a parameter, a global, or an element of a variable, such asParseofself.parser.Parse(data), never creates an object. - A call of a variable whose type is a class of the archive counts as a call to
__call__of that class.
Stereocode reads four built-in lists for Python. The list files of the options -p, -c, -s, and -q add entries to these lists under the section [Python], as the README states. Each list below opens with a click.
Primitive types (12 entries)
A type of this list makes no method a collaborator and no return type of a factory.
Any, bool, bytearray, bytes, complex, float, int, Literal, None, NoneType, object, str
Ignored calls (26 entries)
The rules ignore a call of these names. Besides the calls that only report or end the program, such as print and sys.exit, the list holds the built-in functions that stand for an operator, a cast, or the header of a loop in the other languages, such as len and range. A name without a qualifier, such as print, is ignored only as the whole name of a call. cache.set(key) thus remains a call on cache. Other built-in functions, such as sorted and open, are calls of free functions.
bool, breakpoint, bytearray, bytes, complex, dict, enumerate, exit, float, frozenset, int, isinstance, issubclass, len, list, print, quit, range, repr, reversed, set, str, sys.exit, tuple, type, zip
Specifiers and containers (44 entries)
Stereocode strips these entries from a written type before it reads the names of the type. A wrapper or a container thus counts by the types in its arguments, such as Engine of Optional[Engine] or list[Engine]. Each entry is a regular expression, such as \.\.\. for ....
<, >, \.\.\., \|, AbstractSet, Annotated, AsyncGenerator, AsyncIterable, AsyncIterator, Awaitable, Callable, ChainMap, ClassVar, Collection, Coroutine, Counter, DefaultDict, defaultdict, Deque, deque, Dict, dict, Final, FrozenSet, frozenset, Generator, Iterable, Iterator, List, list, Mapping, MutableMapping, MutableSequence, MutableSet, Optional, OrderedDict, Sequence, Set, set, Tuple, tuple, Type, type, Union
Query methods (66 entries)
A call of these methods only reads the variable that the call is on. The list holds the methods of the immutable types str, bytes, int, float, tuple, and frozenset and the methods of list, dict, and set that change nothing.
as_integer_ratio, bit_count, bit_length, capitalize, casefold, center, conjugate, copy, count, decode, difference, encode, endswith, expandtabs, find, format, format_map, get, hex, index, intersection, is_integer, isalnum, isalpha, isascii, isdecimal, isdigit, isdisjoint, isidentifier, islower, isnumeric, isprintable, isspace, issubset, issuperset, istitle, isupper, items, join, keys, ljust, lower, lstrip, partition, removeprefix, removesuffix, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, symmetric_difference, title, to_bytes, translate, union, upper, values, zfill
Each example below is the declaration of an element from the stereotype cases of Stereocode, whose expected stereotypes are written by hand in @stereotype comments. Each link opens the case on the branch develop. The second column gives every stereotype of the element. A stereotype without an example has no case in Python.
TABLE 1. Examples of the method stereotypes in Python.
| Stereotype | Stereotypes of the element | Declaration |
|---|---|---|
| main | main |
def main() -> None: |
| predicate | predicate |
def is_even(value: int) -> bool: |
| property | property |
def perimeter(side: float, sides: int) -> float: |
| global-command | global-command |
def resize(cls, count: int) -> None: |
| command | command |
def fill(values: list[int], value: int) -> None: |
| factory | property factory |
def make_widget(style: int) -> Widget: |
| literal | literal |
def path_separator(): |
| wrapper | wrapper |
def report(value: int) -> None: |
| empty | empty |
def noop(value: int) -> None: |
| unclassified | unclassified |
def show(value: int) -> None: |
TABLE 2. Examples of the free-function stereotypes in Python, which the option -f assigns.
| Stereotype | Stereotypes of the element | Declaration |
|---|---|---|
| boundary | boundary |
class Exporter: |
| commander | minimal-entity commander |
class Counter: |
| controller | controller |
class Spooler: |
| data-class | data-class |
class Pair: |
| data-provider | data-provider |
class Circle: |
| degenerate | entity degenerate |
class Plugin: |
| empty | empty |
class Tag: |
| entity | entity boundary |
class Measure: |
| factory | factory controller |
class WidgetFactory: |
| lazy-class | lazy-class |
class Settings: |
| minimal-entity | minimal-entity commander |
class Counter: |
| pure-controller | pure-controller |
class Dispatcher: |
| small-class | data-class small-class |
class Account: |
TABLE 3. Examples of the class stereotypes in Python, where large-class, lazy-class, data-class, and small-class of a type of another kind take that kind in place of class, such as data-struct.