Package: py2puml
Python to PlantUMLGenerate PlantUML class diagrams to document your Python application.py2pumlusespre-commit hooksandpre-commit.ci Continuous Integrationto enforce commit messages, code formatting and linting for quality and consistency sake.
See thecode conventionssection if you would like to contribute to the project.How it workspy2pumlproduces a class diagramPlantUML scriptrepresenting classes properties (static and instance attributes) and their relations (composition and inheritance relationships).py2pumlinternally uses codeinspection(also calledreflexionin other programming languages) andabstract tree parsingto retrieve relevant information.Minimum Python versions to run py2pumlp2pumluses some code-parsing features that are available only sincePython 3.8(likeast.get_source_segment).
If your codebase uses theint | floatsyntax to define optional types, then you should use Python 3.10 to runpy2puml.To sum it up, use at least Python 3.8 to run py2puml, or a higher version if you use syntax features available only in higher versions.The.python-versionfile indicates the Python version used to develop the library.
It is a file used bypyenvto define the binary used by the project.FeaturesFrom a given path corresponding to a folder containing Python code,py2pumlprocesses each Python module and generates aPlantUML scriptfrom the definitions of various data structures using:inspectionandtype annotationsto detect:static class attributes anddataclassfieldsfields ofnamedtuplesmembers ofenumerationscomposition and inheritance relationships (between your domain classes only, for documentation sake).
The detection of composition relationships relies on type annotations only, assigned values or expressions are never evaluated to prevent unwanted side-effectsparsingabstract syntax treesto detect the instance attributes defined in__init__constructorspy2pumloutputs diagrams in PlantUML syntax, which can be:versioned along your code with a unit-test ensuring its consistency (see thetest_py2puml.py's test_py2puml_model_on_py2uml_domainexample)generated and hosted along other code documentation (better option: generated documentation should not be versioned with the codebase)To generate image files, use the PlantUML runtime, a docker image of the runtime (seethink/plantuml) or of a server (see the CLI documentation below)If you like tools related with PlantUML, you may also be interested in thislucsorel/plantuml-file-loaderproject:
a webpack loader which converts PlantUML files into images during the webpack processing (useful toinclude PlantUML diagrams in your slideswith RevealJS or RemarkJS).InstallInstall fromPyPI:withpip:pipinstallpy2pumlwithpoetry:poetryaddpy2pumlwithpipenv:pipenvinstallpy2pumlUsageCLIOncepy2pumlis installed at the system level, an eponymous command is available in your environment shell.For example, to create the diagram of the classes used bypy2puml, run:py2pumlpy2puml/domainpy2puml.domainThis outputs the following PlantUML content:@startuml py2puml.domain
!pragma useIntermediatePackages false

class py2puml.domain.umlclass.UmlAttribute {
  name: str
  type: str
  static: bool
}
class py2puml.domain.umlclass.UmlClass {
  attributes: List[UmlAttribute]
  is_abstract: bool
}
class py2puml.domain.umlitem.UmlItem {
  name: str
  fqn: str
}
class py2puml.domain.umlenum.Member {
  name: str
  value: str
}
class py2puml.domain.umlenum.UmlEnum {
  members: List[Member]
}
enum py2puml.domain.umlrelation.RelType {
  COMPOSITION: * {static}
  INHERITANCE: <| {static}
}
class py2puml.domain.umlrelation.UmlRelation {
  source_fqn: str
  target_fqn: str
  type: RelType
}
py2puml.domain.umlclass.UmlClass *-- py2puml.domain.umlclass.UmlAttribute
py2puml.domain.umlitem.UmlItem <|-- py2puml.domain.umlclass.UmlClass
py2puml.domain.umlenum.UmlEnum *-- py2puml.domain.umlenum.Member
py2puml.domain.umlitem.UmlItem <|-- py2puml.domain.umlenum.UmlEnum
py2puml.domain.umlrelation.UmlRelation *-- py2puml.domain.umlrelation.RelType
footer Generated by //py2puml//
@endumlUsing PlantUML, this content is rendered as in this diagram:For a full overview of the CLI, run:py2puml--helpThe CLI can also be launched as a python module:python-mpy2pumlpy2puml/domainpy2puml.domainPipe the result of the CLI with a PlantUML server for instantaneous documentation (rendered by ImageMagick):# runs a local PlantUML server from a docker container:dockerrun-d--rm-p1234:8080--nameplantumlserverplantuml/plantuml-server:jetty

py2pumlpy2puml/domainpy2puml.domain|curl-XPOST--data-binary@-http://localhost:1234/svg/--output-|display# stops the container when you don't need it anymore, restarts it laterdockerstopplantumlserver
dockerstartplantumlserverPython APIFor example, to create the diagram of the domain classes used bypy2puml:import thepy2pumlfunction in your script:frompy2puml.py2pumlimportpy2pumlif__name__=='__main__':# outputs the PlantUML content in the terminalprint(''.join(py2puml('py2puml/domain','py2puml.domain')))# writes the PlantUML content in a filewithopen('py2puml/py2puml.domain.puml','w',encoding='utf8')aspuml_file:puml_file.writelines(py2puml('py2puml/domain','py2puml.domain'))running it outputs the previous PlantUML diagram in the terminal and writes it in a file.Tests# directly with poetrypoetryrunpytest-v# in a virtual environmentpython3-mpytest-vCode coverage (withmissed branch statements):poetryrunpytest-v--cov=py2puml--cov-branch--cov-reportterm-missing--cov-fail-under93Changelog0.9.1: improved 0.7.2 by adding the current working directory at the beginning of the sys.path to resolve the module paths of the project being inspected.
Fix url to PlantUML logo on the README.md page0.9.0: add classes defined in__init__.pyfiles to plantuml output; replaced yapf by the ruff formatter0.8.1: delegated the grouping of nested namespaces (see0.7.0) to the PlantUML binary, which handles it natively0.8.0: added support for union types, and github actions (pre-commit hooks + automated tests)0.7.2: added the current working directory to the import path to make py2puml work in any directory or in native virtual environment (not handled by poetry)0.7.1: removed obsolete part of documentation: deeply compound types are now well handled (by version0.7.0)0.7.0: improved the generated PlantUML documentation (added the namespace structure of the code base, homogenized type  between inspection and parsing), improved relationships management (handle forward references, deduplicate relationships)0.6.1: handle class names with digits0.6.0: handle abstract classes0.5.4: fixed the packaging so that the contribution guide is included in the published package0.5.3: handle constructors decorated by wrapping decorators (decorators making uses offunctools.wrap)0.5.2: specify in pyproject.toml that py2puml requires python 3.8+ (ast.get_source_segmentwas introduced in 3.8)0.5.1: prevent from parsing inherited constructors0.5.0: handle instance attributes in class constructors, add code coverage of unit tests0.4.0: add a simple CLI0.3.1: inspect sub-folders recursively0.3.0: handle classes derived from namedtuples (attribute types areAny)0.2.0: handle inheritance relationships and enums0.1.3: first release, handle all modules of a folder and compositions of domain classesLicenceUnless stated otherwise all works are licensed under theMIT license, a copy of which is includedhere.ContributionsLuc Sorel-GiffoDoyou JungJulien JerphanionLuis Fernando Villanueva PérezKonstantin ZangerlePull requestsPull-requests are welcome and will be processed on a best-effort basis.Pull requests must follow the guidelines enforced by thepre-commithooks:commit messages must follow the Angular conventions enforced by thecommitlinthookcode formatting must follow the conventions enforced by theisortandruff-formathookscode linting should not detect code smells in your contributions, this is checked by theruffhookPlease also follow thecontributing guideto ease your contribution.Code conventionsThe code conventions are described and enforced bypre-commit hooksto maintain consistency across the code base.
The hooks are declared in the.pre-commit-config.yamlfile.Set the git hooks (pre-commit and commit-msg types):poetryrunpre-commitinstall--hook-typepre-commit--hook-typecommit-msgBefore committing, you can check your changes with:# put all your changes in the git staging areagitadd-A# all hookspoetryrunpre-commitrun--all-files# a specific hookpoetryrunpre-commitrunruff--all-filesCommit messagesPlease, follow theconventions of the Angular teamfor commit messages.
When merging your pull-request, the new version of the project will be derived from the messages.Code formattingThis project usesisortandruff-formatto format the code.
The guidelines are expressed in their respective sections in thepyproject.tomlfile.Best practicesThis project uses therufflinter, which is configured in its section in thepyproject.tomlfile.Current limitationsregardinginspectiontype hinting is optional when writing Python code and discarded when it is executed, as mentionned in thetyping official documentation. The quality of the diagram output bypy2pumldepends on the reliability with which the type annotations were writtenThe Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.regarding the detection of instance attributes withAST parsing:only constructors are visited, attributes assigned in other functions won't be documentedattribute types are inferred from type annotations:of the attribute itselfof the variable assigned to the attribute: a signature parameter or a locale variableto avoid side-effects, no code is executed nor interpretedAlternativesIfpy2pumldoes not meet your needs (suggestions and pull-requests arewelcome), you can have a look at these projects which follow other approaches (AST, linting, modeling):pyreverse, which includes a PlantUML printersince version 2.10.0cb109/pyplantumldeadbok/py-puml-toolscaballero/genUML