Skip to content

# `` infixowl

RDFLib Python binding for OWL Abstract Syntax

OWL Constructor | DL Syntax | Manchester OWL Syntax | Example
--- | --- | --- | ---
`intersectionOf` | C ∩ D | C AND D | Human AND Male
`unionOf` | C ∪ D | C OR D | Man OR Woman
`complementOf` | ¬C | NOT C | NOT Male
`oneOf` | {a} ∪ {b}… | {a b …} | {England Italy Spain}
`someValuesFrom` | ∃ R C | R SOME C | hasColleague SOME Professor
`allValuesFrom` | ∀ R C | R ONLY C | hasColleague ONLY Professor
`minCardinality` | ≥ N R | R MIN 3 | hasColleague MIN 3
`maxCardinality` | ≤ N R | R MAX 3 | hasColleague MAX 3
`cardinality` | = N R | R EXACTLY 3 | hasColleague EXACTLY 3
`hasValue` | ∃ R.{a} | R VALUE a | hasColleague VALUE Matthew

See: - http://www.w3.org/TR/owl-semantics/syntax.html - http://owl-workshop.man.ac.uk/acceptedLong/submission_9.pdf

3.2.3 Axioms for complete classes without using owl:equivalentClass

Named class description of type 2 (with owl:oneOf) or type 4-6 (with owl:intersectionOf, owl:unionOf or owl:complementOf

Uses Manchester Syntax for `__repr__`

    >>> exNs = Namespace("http://example.com/")
    >>> g = Graph()
    >>> g.bind("ex", exNs, override=False)

Now we have an empty graph, we can construct OWL classes in it using the Python classes defined in this module

    >>> a = Class(exNs.Opera, graph=g)

Now we can assert rdfs:subClassOf and owl:equivalentClass relationships (in the underlying graph) with other classes using the ‘subClassOf’ and ‘equivalentClass’ descriptors which can be set to a list of objects for the corresponding predicates.

    >>> a.subClassOf = [exNs.MusicalWork]

We can then access the rdfs:subClassOf relationships

    >>> print(list(a.subClassOf))
    [Class: ex:MusicalWork ]

This can also be used against already populated graphs:

    >>> owlGraph = Graph().parse(str(OWL))
    >>> list(Class(OWL.Class, graph=owlGraph).subClassOf)
    [Class: rdfs:Class ]

Operators are also available. For instance we can add ex:Opera to the extension of the ex:CreativeWork class via the ‘+=’ operator

    >>> a
    Class: ex:Opera SubClassOf: ex:MusicalWork
    >>> b = Class(exNs.CreativeWork, graph=g)
    >>> b += a
    >>> print(sorted(a.subClassOf, key=lambda c:c.identifier))
    [Class: ex:CreativeWork , Class: ex:MusicalWork ]

And we can then remove it from the extension as well

    >>> b -= a
    >>> a
    Class: ex:Opera SubClassOf: ex:MusicalWork

Boolean class constructions can also be created with Python operators. For example, The | operator can be used to construct a class consisting of a owl:unionOf the operands:

    >>> c =  a | b | Class(exNs.Work, graph=g)
    >>> c
    ( ex:Opera OR ex:CreativeWork OR ex:Work )

Boolean class expressions can also be operated as lists (using python list operators)

    >>> del c[c.index(Class(exNs.Work, graph=g))]
    >>> c
    ( ex:Opera OR ex:CreativeWork )

The ‘&’ operator can be used to construct class intersection:

    >>> woman = Class(exNs.Female, graph=g) & Class(exNs.Human, graph=g)
    >>> woman.identifier = exNs.Woman
    >>> woman
    ( ex:Female AND ex:Human )
    >>> len(woman)
    2

Enumerated classes can also be manipulated

    >>> contList = [Class(exNs.Africa, graph=g), Class(exNs.NorthAmerica, graph=g)]
    >>> EnumeratedClass(members=contList, graph=g)
    { ex:Africa ex:NorthAmerica }

owl:Restrictions can also be instantiated:

    >>> Restriction(exNs.hasParent, graph=g, allValuesFrom=exNs.Human)
    ( ex:hasParent ONLY ex:Human )

Restrictions can also be created using Manchester OWL syntax in ‘colloquial’ Python

    >>> exNs.hasParent @ some @ Class(exNs.Physician, graph=g)
    ( ex:hasParent SOME ex:Physician )
    >>> Property(exNs.hasParent, graph=g) @ max @ Literal(1)
    ( ex:hasParent MAX 1 )
    >>> print(g.serialize(format='pretty-xml'))  # doctest: +SKIP

Classes:

- `AnnotatableTerms` –

  Terms in an OWL ontology with rdfs:label and rdfs:comment

- `BooleanClass` –

  See: http://www.w3.org/TR/owl-ref/#Boolean

- `Callable` –
- `Class` –

  ‘General form’ for classes:

- `ClassNamespaceFactory` –
- `EnumeratedClass` –

  Class for owl:oneOf forms:

- `Individual` –

  A typed individual, the base class of the InfixOWL classes.

- `Infix` –
- `MalformedClass` –

  Deprecated

- `MalformedClassError` –
- `OWLRDFListProxy` –
- `Ontology` –

  The owl ontology metadata

- `Property` –

  ```

- `Restriction` –

  ```

Functions:

- `AllClasses` –
- `AllDifferent` –

  TODO: implement this function

- `AllProperties` –
- `CastClass` –
- `CommonNSBindings` –

  Takes a graph and binds the common namespaces (rdf,rdfs, & owl)

- `ComponentTerms` –

  Takes a Class instance and returns a generator over the classes that

- `DeepClassClear` –

  Recursively clear the given class, continuing

- `GetIdentifiedClasses` –
- `classOrIdentifier` –
- `classOrTerm` –
- `generateQName` –
- `manchesterSyntax` –

  Core serialization

- `propertyOrIdentifier` –

Attributes:

- `ACE_NS` –
- `CLASS_RELATIONS` –
- `PropertyAbstractSyntax` –
- `exactly` –
- `max` –
- `min` –
- `nsBinds` –
- `only` –
- `some` –
- `value` –

## `` ACE_NS `module-attribute`

    ACE_NS = Namespace('http://attempto.ifi.uzh.ch/ace_lexicon#')

## `` BooleanPredicates `module-attribute`

    BooleanPredicates = [intersectionOf, unionOf]

## `` CLASS_RELATIONS `module-attribute`

    CLASS_RELATIONS = difference([onProperty, allValuesFrom, hasValue, someValuesFrom, inverseOf, imports, versionInfo, backwardCompatibleWith, incompatibleWith, unionOf, intersectionOf, oneOf])

## `` PropertyAbstractSyntax `module-attribute`

    PropertyAbstractSyntax = "\n%s( %s { %s }\n%s\n{ 'super(' datavaluedPropertyID ')'} ['Functional']\n{ domain( %s ) } { range( %s ) } )"

## `` __all__ `module-attribute`

    __all__ = ['ACE_NS', 'AllClasses', 'AllDifferent', 'AllProperties', 'AnnotatableTerms', 'BooleanClass', 'CLASS_RELATIONS', 'Callable', 'CastClass', 'Class', 'ClassNamespaceFactory', 'CommonNSBindings', 'ComponentTerms', 'DeepClassClear', 'EnumeratedClass', 'GetIdentifiedClasses', 'Individual', 'Infix', 'MalformedClass', 'MalformedClassError', 'OWLRDFListProxy', 'Ontology', 'Property', 'PropertyAbstractSyntax', 'Restriction', 'classOrIdentifier', 'classOrTerm', 'exactly', 'generateQName', 'manchesterSyntax', 'max', 'min', 'nsBinds', 'only', 'propertyOrIdentifier', 'some', 'value']

## `` exactly `module-attribute`

    exactly = Infix(lambda prop, _class: Restriction(prop, graph=graph, cardinality=_class))

## `` logger `module-attribute`

    logger = getLogger(__name__)

From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122

Python has the wonderful “in” operator and it would be nice to have additional infix operator like this. This recipe shows how (almost) arbitrary infix operators can be defined.

## `` max `module-attribute`

    max = Infix(lambda prop, _class: Restriction(prop, graph=graph, maxCardinality=_class))

## `` min `module-attribute`

    min = Infix(lambda prop, _class: Restriction(prop, graph=graph, minCardinality=_class))

## `` nsBinds `module-attribute`

    nsBinds = {'skos': 'http://www.w3.org/2004/02/skos/core#', 'rdf': RDF, 'rdfs': RDFS, 'owl': OWL, 'list': URIRef('http://www.w3.org/2000/10/swap/list#'), 'dc': 'http://purl.org/dc/elements/1.1/'}

## `` only `module-attribute`

    only = Infix(lambda prop, _class: Restriction(prop, graph=graph, allValuesFrom=_class))

## `` some `module-attribute`

    some = Infix(lambda prop, _class: Restriction(prop, graph=graph, someValuesFrom=_class))

## `` value `module-attribute`

    value = Infix(lambda prop, _class: Restriction(prop, graph=graph, value=_class))

## `` AnnotatableTerms

    AnnotatableTerms(identifier, graph=None, nameAnnotation=None, nameIsLabel=False)

Bases: `Individual`

Terms in an OWL ontology with rdfs:label and rdfs:comment

Interface with ATTEMPTO (http://attempto.ifi.uzh.ch/site)

#### Verbalisation of OWL entity IRIS

##### How are OWL entity IRIs verbalized?

The OWL verbalizer maps OWL entity IRIs to ACE content words such that

- OWL individuals map to ACE proper names (PN)
- OWL classes map to ACE common nouns (CN)
- OWL properties map to ACE transitive verbs (TV)

There are 6 morphological categories that determine the surface form of an IRI:

- singular form of a proper name (e.g. John)
- singular form of a common noun (e.g. man)
- plural form of a common noun (e.g. men)
- singular form of a transitive verb (e.g. mans)
- plural form of a transitive verb (e.g. man)
- past participle form a transitive verb (e.g. manned)

The user has full control over the eventual surface forms of the IRIs but has to choose them in terms of the above categories. Furthermore,

- the surface forms must be legal ACE content words (e.g. they should not contain punctuation symbols);
- the mapping of IRIs to surface forms must be bidirectional within the same word class, in order to be able to (if needed) parse the verbalization back into OWL in a semantics preserving way.

##### Using the lexicon

It is possible to specify the mapping of IRIs to surface forms using the following annotation properties:

    http://attempto.ifi.uzh.ch/ace_lexicon#PN_sg
    http://attempto.ifi.uzh.ch/ace_lexicon#CN_sg
    http://attempto.ifi.uzh.ch/ace_lexicon#CN_pl
    http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg
    http://attempto.ifi.uzh.ch/ace_lexicon#TV_pl
    http://attempto.ifi.uzh.ch/ace_lexicon#TV_vbg

For example, the following axioms state that if the IRI “#man” is used as a plural common noun, then the wordform men must be used by the verbalizer. If, however, it is used as a singular transitive verb, then mans must be used.

    <AnnotationAssertion>
        <AnnotationProperty IRI="http://attempto.ifi.uzh.ch/ace_lexicon#CN_pl"/>
        <IRI>#man</IRI>
        <Literal datatypeIRI="&xsd;string">men</Literal>
    </AnnotationAssertion>

    <AnnotationAssertion>
        <AnnotationProperty IRI="http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg"/>
        <IRI>#man</IRI>
        <Literal datatypeIRI="&xsd;string">mans</Literal>
    </AnnotationAssertion>

Methods:

- `handleAnnotation` –
- `setupACEAnnotations` –

Attributes:

- `comment` –
- `label` –
- `seeAlso` –

Source code in `rdflib/extras/infixowl.py`

    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649

    def __init__(
        self,
        identifier,
        graph=None,
        nameAnnotation=None,  # noqa: N803
        nameIsLabel=False,  # noqa: N803
    ):
        super(AnnotatableTerms, self).__init__(identifier, graph)
        if nameAnnotation:
            self.setupACEAnnotations()
            self.PN_sgprop.extent = [
                (self.identifier, self.handleAnnotation(nameAnnotation))
            ]
            if nameIsLabel:
                self.label = [nameAnnotation]

### `` comment `class-attribute` `instance-attribute`

    comment = property(_get_comment, _set_comment, _del_comment)

### `` label `class-attribute` `instance-attribute`

    label = property(_get_label, _set_label, _delete_label)

### `` seeAlso `class-attribute` `instance-attribute`

    seeAlso = property(_get_seealso, _set_seealso, _del_seealso)

### `` handleAnnotation

    handleAnnotation(val)

Source code in `rdflib/extras/infixowl.py`

    651
    652

    def handleAnnotation(self, val):  # noqa: N802
        return val if isinstance(val, Literal) else Literal(val)

### `` setupACEAnnotations

    setupACEAnnotations()

Source code in `rdflib/extras/infixowl.py`

    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685

    def setupACEAnnotations(self):  # noqa: N802
        self.graph.bind("ace", ACE_NS, override=False)

        # PN_sg singular form of a proper name ()
        self.PN_sgprop = Property(
            ACE_NS.PN_sg, baseType=OWL.AnnotationProperty, graph=self.graph
        )

        # CN_sg singular form of a common noun
        self.CN_sgprop = Property(
            ACE_NS.CN_sg, baseType=OWL.AnnotationProperty, graph=self.graph
        )

        # CN_pl plural form of a common noun
        self.CN_plprop = Property(
            ACE_NS.CN_pl, baseType=OWL.AnnotationProperty, graph=self.graph
        )

        # singular form of a transitive verb
        self.tv_sgprop = Property(
            ACE_NS.TV_sg, baseType=OWL.AnnotationProperty, graph=self.graph
        )

        # plural form of a transitive verb
        self.tv_plprop = Property(
            ACE_NS.TV_pl, baseType=OWL.AnnotationProperty, graph=self.graph
        )

        # past participle form a transitive verb
        self.tv_vbgprop = Property(
            ACE_NS.TV_vbg, baseType=OWL.AnnotationProperty, graph=self.graph
        )

## `` BooleanClass

    BooleanClass(identifier=None, operator=intersectionOf, members=None, graph=None)

Bases: `OWLRDFListProxy`, `Class`

See: http://www.w3.org/TR/owl-ref/#Boolean

owl:complementOf is an attribute of Class, however

Methods:

- `__or__` –

  Adds other to the list and returns self

- `__repr__` –

  Returns the Manchester Syntax equivalent for this class

- `changeOperator` –

  Converts a unionOf / intersectionOf class expression into one

- `copy` –

  Create a copy of this class

- `isPrimitive` –
- `serialize` –

Attributes:

- `getIntersections` –
- `getUnions` –

Source code in `rdflib/extras/infixowl.py`

    1677
    1678
    1679
    1680
    1681
    1682
    1683
    1684
    1685
    1686
    1687
    1688
    1689
    1690
    1691
    1692
    1693
    1694
    1695

    def __init__(
        self, identifier=None, operator=OWL.intersectionOf, members=None, graph=None
    ):
        if operator is None:
            props = []
            for _s, p, _o in graph.triples_choices(
                (identifier, [OWL.intersectionOf, OWL.unionOf], None)
            ):
                props.append(p)
                operator = p
            assert len(props) == 1, repr(props)
        Class.__init__(self, identifier, graph=graph)
        assert operator in [OWL.intersectionOf, OWL.unionOf], str(operator)
        self._operator = operator
        rdf_list = list(self.graph.objects(predicate=operator, subject=self.identifier))
        assert (
            not members or not rdf_list
        ), "This is a previous boolean class description."
        OWLRDFListProxy.__init__(self, rdf_list, members)

### `` getIntersections `class-attribute` `instance-attribute`

    getIntersections = Callable(getIntersections)

### `` getUnions `class-attribute` `instance-attribute`

    getUnions = Callable(getUnions)

### `` __or__

    __or__(other)

Adds other to the list and returns self

Source code in `rdflib/extras/infixowl.py`

    1763
    1764
    1765
    1766
    1767
    1768
    1769

    def __or__(self, other):
        """
        Adds other to the list and returns self
        """
        assert self._operator == OWL.unionOf
        self._rdfList.append(classOrIdentifier(other))
        return self

### `` __repr__

    __repr__()

Returns the Manchester Syntax equivalent for this class

Source code in `rdflib/extras/infixowl.py`

    1753
    1754
    1755
    1756
    1757
    1758
    1759
    1760
    1761

    def __repr__(self):
        """
        Returns the Manchester Syntax equivalent for this class
        """
        return manchesterSyntax(
            self._rdfList.uri if isinstance(self._rdfList, Collection) else BNode(),
            self.graph,
            boolean=self._operator,
        )

### `` changeOperator

    changeOperator(newOperator)

Converts a unionOf / intersectionOf class expression into one that instead uses the given operator

    >>> testGraph = Graph()
    >>> Individual.factoryGraph = testGraph
    >>> EX = Namespace("http://example.com/")
    >>> testGraph.bind("ex", EX, override=False)
    >>> fire = Class(EX.Fire)
    >>> water = Class(EX.Water)
    >>> testClass = BooleanClass(members=[fire,water])
    >>> testClass
    ( ex:Fire AND ex:Water )
    >>> testClass.changeOperator(OWL.unionOf)
    >>> testClass
    ( ex:Fire OR ex:Water )
    >>> try:
    ...     testClass.changeOperator(OWL.unionOf)
    ... except Exception as e:
    ...     print(e)  # doctest: +SKIP
    The new operator is already being used!

Source code in `rdflib/extras/infixowl.py`

    1722
    1723
    1724
    1725
    1726
    1727
    1728
    1729
    1730
    1731
    1732
    1733
    1734
    1735
    1736
    1737
    1738
    1739
    1740
    1741
    1742
    1743
    1744
    1745
    1746
    1747
    1748
    1749
    1750
    1751

    def changeOperator(self, newOperator):  # noqa: N802, N803
        """
        Converts a unionOf / intersectionOf class expression into one
        that instead uses the given operator

        ```python
        >>> testGraph = Graph()
        >>> Individual.factoryGraph = testGraph
        >>> EX = Namespace("http://example.com/")
        >>> testGraph.bind("ex", EX, override=False)
        >>> fire = Class(EX.Fire)
        >>> water = Class(EX.Water)
        >>> testClass = BooleanClass(members=[fire,water])
        >>> testClass
        ( ex:Fire AND ex:Water )
        >>> testClass.changeOperator(OWL.unionOf)
        >>> testClass
        ( ex:Fire OR ex:Water )
        >>> try:
        ...     testClass.changeOperator(OWL.unionOf)
        ... except Exception as e:
        ...     print(e)  # doctest: +SKIP
        The new operator is already being used!

        ```
        """
        assert newOperator != self._operator, "The new operator is already being used!"
        self.graph.remove((self.identifier, self._operator, self._rdfList.uri))
        self.graph.add((self.identifier, newOperator, self._rdfList.uri))
        self._operator = newOperator

### `` copy

    copy()

Create a copy of this class

Source code in `rdflib/extras/infixowl.py`

    1697
    1698
    1699
    1700
    1701
    1702
    1703
    1704

    def copy(self):
        """
        Create a copy of this class
        """
        copy_of_class = BooleanClass(
            operator=self._operator, members=list(self), graph=self.graph
        )
        return copy_of_class

### `` isPrimitive

    isPrimitive()

Source code in `rdflib/extras/infixowl.py`

    1719
    1720

    def isPrimitive(self):  # noqa: N802
        return False

### `` serialize

    serialize(graph)

Source code in `rdflib/extras/infixowl.py`

    1706
    1707
    1708
    1709
    1710
    1711
    1712
    1713
    1714
    1715
    1716
    1717

    def serialize(self, graph):
        clonedlist = Collection(graph, BNode())
        for cl in self._rdfList:
            clonedlist.append(cl)
            CastClass(cl, self.graph).serialize(graph)

        graph.add((self.identifier, self._operator, clonedlist.uri))

        for s, p, o in self.graph.triples((self.identifier, None, None)):
            if p != self._operator:
                graph.add((s, p, o))
        self._serialize(graph)

## `` BooleanClassExtentHelper

    BooleanClassExtentHelper(operator)

    >>> testGraph = Graph()
    >>> Individual.factoryGraph = testGraph
    >>> EX = Namespace("http://example.com/")
    >>> testGraph.bind("ex", EX, override=False)
    >>> fire = Class(EX.Fire)
    >>> water = Class(EX.Water)
    >>> testClass = BooleanClass(members=[fire, water])
    >>> testClass2 = BooleanClass(
    ...     operator=OWL.unionOf, members=[fire, water])
    >>> for c in BooleanClass.getIntersections():
    ...     print(c)  # doctest: +SKIP
    ( ex:Fire AND ex:Water )
    >>> for c in BooleanClass.getUnions():
    ...     print(c) #doctest: +SKIP
    ( ex:Fire OR ex:Water )

Methods:

- `__call__` –

Attributes:

- `operator` –

Source code in `rdflib/extras/infixowl.py`

    1637
    1638

    def __init__(self, operator):
        self.operator = operator

### `` operator `instance-attribute`

    operator = operator

### `` __call__

    __call__(f)

Source code in `rdflib/extras/infixowl.py`

    1640
    1641
    1642
    1643
    1644
    1645

    def __call__(self, f):
        def _getExtent():  # noqa: N802
            for c in Individual.factoryGraph.subjects(self.operator):
                yield BooleanClass(c, operator=self.operator)

        return _getExtent

## `` Callable

    Callable(anycallable)

Methods:

- `__call__` –

Source code in `rdflib/extras/infixowl.py`

    1649
    1650

    def __init__(self, anycallable):
        self._callfn = anycallable

### `` __call__

    __call__(*args, **kwargs)

Source code in `rdflib/extras/infixowl.py`

    1652
    1653

    def __call__(self, *args, **kwargs):
        return self._callfn(*args, **kwargs)

## `` Class

    Class(identifier=None, subClassOf=None, equivalentClass=None, disjointWith=None, complementOf=None, graph=None, skipOWLClassMembership=False, comment=None, nounAnnotations=None, nameAnnotation=None, nameIsLabel=False)

Bases: `AnnotatableTerms`

‘General form’ for classes:

The Manchester Syntax (supported in Protege) is used as the basis for the form of this class

See: http://owl-workshop.man.ac.uk/acceptedLong/submission_9.pdf:

    [Annotation]
    ‘Class:’ classID {Annotation
    ( (‘SubClassOf:’ ClassExpression)
    | (‘EquivalentTo’ ClassExpression)
    | (’DisjointWith’ ClassExpression)) }

Appropriate excerpts from OWL Reference:

”.. Subclass axioms provide us with partial definitions: they represent necessary but not sufficient conditions for establishing class membership of an individual.”

”.. A class axiom may contain (multiple) owl:equivalentClass statements”

”..A class axiom may also contain (multiple) owl:disjointWith statements..”

”..An owl:complementOf property links a class to precisely one class description.”

Methods:

- `__and__` –

  Construct an anonymous class description consisting of the

- `__eq__` –
- `__hash__` –

  > > > b = Class(OWL.Restriction)

- `__iadd__` –
- `__invert__` –

  Shorthand for Manchester syntax’s not operator

- `__isub__` –
- `__or__` –

  Construct an anonymous class description consisting of the union of

- `__repr__` –
- `isPrimitive` –
- `manchesterClass` –

  Returns the Manchester Syntax equivalent for this class

- `serialize` –
- `setupNounAnnotations` –
- `subSumpteeIds` –

Attributes:

- `annotation` –
- `comment` –
- `complementOf` –
- `disjointWith` –
- `equivalentClass` –
- `extent` –
- `extentQuery` –
- `parents` –
- `subClassOf` –

Source code in `rdflib/extras/infixowl.py`

    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119

    def __init__(
        self,
        identifier=None,
        subClassOf=None,  # noqa: N803
        equivalentClass=None,  # noqa: N803
        disjointWith=None,  # noqa: N803
        complementOf=None,  # noqa: N803
        graph=None,
        skipOWLClassMembership=False,  # noqa: N803
        comment=None,
        nounAnnotations=None,  # noqa: N803
        nameAnnotation=None,  # noqa: N803
        nameIsLabel=False,  # noqa: N803
    ):
        super(Class, self).__init__(identifier, graph, nameAnnotation, nameIsLabel)

        if nounAnnotations:
            self.setupNounAnnotations(nounAnnotations)
        if (
            not skipOWLClassMembership
            and (self.identifier, RDF.type, OWL.Class) not in self.graph
            and (self.identifier, RDF.type, OWL.Restriction) not in self.graph
        ):
            self.graph.add((self.identifier, RDF.type, OWL.Class))

        self.subClassOf = [] if subClassOf is None else subClassOf
        self.equivalentClass = [] if equivalentClass is None else equivalentClass
        self.disjointWith = [] if disjointWith is None else disjointWith
        if complementOf:
            self.complementOf = complementOf
        self.comment = [] if comment is None else comment

### `` annotation `class-attribute` `instance-attribute`

    annotation = property(_get_annotation, lambda x: x)

### `` comment `instance-attribute`

    comment = [] if comment is None else comment

### `` complementOf `class-attribute` `instance-attribute`

    complementOf = property(_get_complementof, _set_complementof, _del_complementof)

### `` disjointWith `class-attribute` `instance-attribute`

    disjointWith = property(_get_disjointwith, _set_disjointwith, _del_disjointwith)

### `` equivalentClass `class-attribute` `instance-attribute`

    equivalentClass = property(_get_equivalentclass, _set_equivalentclass, _del_equivalentclass)

### `` extent `class-attribute` `instance-attribute`

    extent = property(_get_extent, _set_extent, _del_type)

### `` extentQuery `class-attribute` `instance-attribute`

    extentQuery = property(_get_extentquery, _set_extentquery)

### `` parents `class-attribute` `instance-attribute`

    parents = property(_get_parents)

### `` subClassOf `class-attribute` `instance-attribute`

    subClassOf = property(_get_subclassof, _set_subclassof, _del_subclassof)

### `` __and__

    __and__(other)

Construct an anonymous class description consisting of the intersection of this class and ‘other’ and return it

Chaining 3 intersections

    >>> exNs = Namespace("http://example.com/")
    >>> g = Graph()
    >>> g.bind("ex", exNs, override=False)
    >>> female = Class(exNs.Female, graph=g)
    >>> human = Class(exNs.Human, graph=g)
    >>> youngPerson = Class(exNs.YoungPerson, graph=g)
    >>> youngWoman = female & human & youngPerson
    >>> youngWoman  # doctest: +SKIP
    ex:YoungPerson THAT ( ex:Female AND ex:Human )
    >>> isinstance(youngWoman, BooleanClass)
    True
    >>> isinstance(youngWoman.identifier, BNode)
    True

Source code in `rdflib/extras/infixowl.py`

    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206
    1207
    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217

    def __and__(self, other):
        """
        Construct an anonymous class description consisting of the
        intersection of this class and 'other' and return it

        Chaining 3 intersections

        ```python
        >>> exNs = Namespace("http://example.com/")
        >>> g = Graph()
        >>> g.bind("ex", exNs, override=False)
        >>> female = Class(exNs.Female, graph=g)
        >>> human = Class(exNs.Human, graph=g)
        >>> youngPerson = Class(exNs.YoungPerson, graph=g)
        >>> youngWoman = female & human & youngPerson
        >>> youngWoman  # doctest: +SKIP
        ex:YoungPerson THAT ( ex:Female AND ex:Human )
        >>> isinstance(youngWoman, BooleanClass)
        True
        >>> isinstance(youngWoman.identifier, BNode)
        True

        ```
        """
        return BooleanClass(
            operator=OWL.intersectionOf, members=[self, other], graph=self.graph
        )

### `` __eq__

    __eq__(other)

Source code in `rdflib/extras/infixowl.py`

    1162
    1163
    1164

    def __eq__(self, other):
        assert isinstance(other, Class), repr(other)
        return self.identifier == other.identifier

### `` __hash__

    __hash__()

> > > b = Class(OWL.Restriction) c = Class(OWL.Restriction) len(set([b,c])) 1

Source code in `rdflib/extras/infixowl.py`

    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160

    def __hash__(self):
        """
        >>> b = Class(OWL.Restriction)
        >>> c = Class(OWL.Restriction)
        >>> len(set([b,c]))
        1
        """
        return hash(self.identifier)

### `` __iadd__

    __iadd__(other)

Source code in `rdflib/extras/infixowl.py`

    1166
    1167
    1168
    1169

    def __iadd__(self, other):
        assert isinstance(other, Class)
        other.subClassOf = [self]
        return self

### `` __invert__

    __invert__()

Shorthand for Manchester syntax’s not operator

Source code in `rdflib/extras/infixowl.py`

    1176
    1177
    1178
    1179
    1180

    def __invert__(self):
        """
        Shorthand for Manchester syntax's not operator
        """
        return Class(complementOf=self)

### `` __isub__

    __isub__(other)

Source code in `rdflib/extras/infixowl.py`

    1171
    1172
    1173
    1174

    def __isub__(self, other):
        assert isinstance(other, Class)
        self.graph.remove((classOrIdentifier(other), RDFS.subClassOf, self.identifier))
        return self

### `` __or__

    __or__(other)

Construct an anonymous class description consisting of the union of this class and ‘other’ and return it

Source code in `rdflib/extras/infixowl.py`

    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189

    def __or__(self, other):
        """
        Construct an anonymous class description consisting of the union of
        this class and 'other' and return it
        """
        return BooleanClass(
            operator=OWL.unionOf, members=[self, other], graph=self.graph
        )

### `` __repr__

    __repr__()

Source code in `rdflib/extras/infixowl.py`

    1380
    1381

    def __repr__(self):
        return self.manchesterClass(full=False, normalization=True)

### `` isPrimitive

    isPrimitive()

Source code in `rdflib/extras/infixowl.py`

    1355
    1356
    1357
    1358
    1359
    1360
    1361
    1362
    1363
    1364
    1365
    1366
    1367
    1368
    1369

    def isPrimitive(self):  # noqa: N802
        if (self.identifier, RDF.type, OWL.Restriction) in self.graph:
            return False
        # sc = list(self.subClassOf)
        ec = list(self.equivalentClass)
        for _boolclass, p, rdf_list in self.graph.triples_choices(
            # type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, List[URIRef], None]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
            (self.identifier, [OWL.intersectionOf, OWL.unionOf], None)  # type: ignore[arg-type]
        ):
            ec.append(manchesterSyntax(rdf_list, self.graph, boolean=p))
        for _e in ec:
            return False
        if self.complementOf:
            return False
        return True

### `` manchesterClass

    manchesterClass(full=False, normalization=True)

Returns the Manchester Syntax equivalent for this class

Source code in `rdflib/extras/infixowl.py`

    1383
    1384
    1385
    1386
    1387
    1388
    1389
    1390
    1391
    1392
    1393
    1394
    1395
    1396
    1397
    1398
    1399
    1400
    1401
    1402
    1403
    1404
    1405
    1406
    1407
    1408
    1409
    1410
    1411
    1412
    1413
    1414
    1415
    1416
    1417
    1418
    1419
    1420
    1421
    1422
    1423
    1424
    1425
    1426
    1427
    1428
    1429
    1430
    1431
    1432
    1433
    1434
    1435
    1436
    1437
    1438
    1439
    1440
    1441
    1442
    1443
    1444
    1445
    1446
    1447
    1448
    1449
    1450
    1451
    1452
    1453
    1454
    1455
    1456
    1457
    1458
    1459
    1460
    1461
    1462
    1463
    1464
    1465
    1466
    1467

    def manchesterClass(self, full=False, normalization=True):  # noqa: N802
        """
        Returns the Manchester Syntax equivalent for this class
        """
        exprs = []
        sc = list(self.subClassOf)
        ec = list(self.equivalentClass)
        for _boolclass, p, rdf_list in self.graph.triples_choices(
            # type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, List[URIRef], None]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
            (self.identifier, [OWL.intersectionOf, OWL.unionOf], None)  # type: ignore[arg-type]
        ):
            ec.append(manchesterSyntax(rdf_list, self.graph, boolean=p))
        dc = list(self.disjointWith)
        c = self.complementOf
        if c:
            dc.append(c)
        klasskind = ""
        label = list(self.graph.objects(self.identifier, RDFS.label))
        # type error: Incompatible types in assignment (expression has type "str", variable has type "List[Node]")
        # type error: Unsupported operand types for + ("str" and "Node")
        label = label and "(" + label[0] + ")" or ""  # type: ignore[assignment, operator]
        if sc:
            if full:
                scjoin = "\n                "
            else:
                scjoin = ", "
            nec_statements = [
                isinstance(s, Class)
                and isinstance(self.identifier, BNode)
                and repr(CastClass(s, self.graph))
                or
                # repr(BooleanClass(classOrIdentifier(s),
                #                  operator=None,
                #                  graph=self.graph)) or
                manchesterSyntax(classOrIdentifier(s), self.graph)
                for s in sc
            ]
            if nec_statements:
                klasskind = "Primitive Type %s" % label
            exprs.append(
                "SubClassOf: %s" % scjoin.join([str(n) for n in nec_statements])
            )
            if full:
                exprs[-1] = "\n    " + exprs[-1]
        if ec:
            nec_suff_statements = [
                isinstance(s, str)
                and s
                or manchesterSyntax(classOrIdentifier(s), self.graph)
                for s in ec
            ]
            if nec_suff_statements:
                klasskind = "A Defined Class %s" % label
            exprs.append("EquivalentTo: %s" % ", ".join(nec_suff_statements))
            if full:
                exprs[-1] = "\n    " + exprs[-1]
        if dc:
            exprs.append(
                "DisjointWith %s\n"
                % "\n                 ".join(
                    [manchesterSyntax(classOrIdentifier(s), self.graph) for s in dc]
                )
            )
            if full:
                exprs[-1] = "\n    " + exprs[-1]
        descr = list(self.graph.objects(self.identifier, RDFS.comment))
        if full and normalization:
            klassdescr = (
                klasskind
                and "\n    ## %s ##" % klasskind
                + (descr and "\n    %s" % descr[0] or "")
                + " . ".join(exprs)
                or " . ".join(exprs)
            )
        else:
            klassdescr = (
                full
                and (descr and "\n    %s" % descr[0] or "")
                or "" + " . ".join(exprs)
            )
        return (
            isinstance(self.identifier, BNode)
            and "Some Class "
            or "Class: %s " % self.qname
        ) + klassdescr

### `` serialize

    serialize(graph)

Source code in `rdflib/extras/infixowl.py`

    1068
    1069
    1070
    1071

    def serialize(self, graph):
        for fact in self.graph.triples((self.identifier, None, None)):
            graph.add(fact)
        self._serialize(graph)

### `` setupNounAnnotations

    setupNounAnnotations(noun_annotations)

Source code in `rdflib/extras/infixowl.py`

    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087

    def setupNounAnnotations(self, noun_annotations):  # noqa: N802
        if isinstance(noun_annotations, tuple):
            cn_sgprop, cn_plprop = noun_annotations
        else:
            cn_sgprop = noun_annotations
            cn_plprop = noun_annotations

        if cn_sgprop:
            self.CN_sgprop.extent = [
                (self.identifier, self.handleAnnotation(cn_sgprop))
            ]
        if cn_plprop:
            self.CN_plprop.extent = [
                (self.identifier, self.handleAnnotation(cn_plprop))
            ]

### `` subSumpteeIds

    subSumpteeIds()

Source code in `rdflib/extras/infixowl.py`

    1371
    1372
    1373

    def subSumpteeIds(self):  # noqa: N802
        for s in self.graph.subjects(predicate=RDFS.subClassOf, object=self.identifier):
            yield s

## `` ClassNamespaceFactory

Bases: `Namespace`

Methods:

- `__getattr__` –
- `__getitem__` –
- `term` –

### `` __getattr__

    __getattr__(name)

Source code in `rdflib/extras/infixowl.py`

    834
    835
    836
    837
    838

    def __getattr__(self, name):
        if name.startswith("__"):  # ignore any special Python names!
            raise AttributeError
        else:
            return self.term(name)

### `` __getitem__

    __getitem__(key, default=None)

Source code in `rdflib/extras/infixowl.py`

    831
    832

    def __getitem__(self, key, default=None):
        return self.term(key)

### `` term

    term(name)

Source code in `rdflib/extras/infixowl.py`

    828
    829

    def term(self, name):
        return Class(URIRef(self + name))

## `` EnumeratedClass

    EnumeratedClass(identifier=None, members=None, graph=None)

Bases: `OWLRDFListProxy`, `Class`

Class for owl:oneOf forms:

OWL Abstract Syntax is used

axiom ::= ‘EnumeratedClass(’ classID [‘Deprecated’] { annotation } { individualID } ‘)’

    >>> exNs = Namespace("http://example.com/")
    >>> g = Graph()
    >>> g.bind("ex", exNs, override=False)
    >>> Individual.factoryGraph = g
    >>> ogbujiBros = EnumeratedClass(exNs.ogbujicBros,
    ...                              members=[exNs.chime,
    ...                                       exNs.uche,
    ...                                       exNs.ejike])
    >>> ogbujiBros  # doctest: +SKIP
    { ex:chime ex:uche ex:ejike }
    >>> col = Collection(g, first(
    ...    g.objects(predicate=OWL.oneOf, subject=ogbujiBros.identifier)))
    >>> sorted([g.qname(item) for item in col])
    ['ex:chime', 'ex:ejike', 'ex:uche']
    >>> print(g.serialize(format='n3'))  # doctest: +SKIP
    @prefix ex: <http://example.com/> .
    @prefix owl: <http://www.w3.org/2002/07/owl#> .
    @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
    <BLANKLINE>
    ex:ogbujicBros a owl:Class;
        owl:oneOf ( ex:chime ex:uche ex:ejike ) .
    <BLANKLINE>
    <BLANKLINE>

Methods:

- `__repr__` –

  Returns the Manchester Syntax equivalent for this class

- `isPrimitive` –
- `serialize` –

Source code in `rdflib/extras/infixowl.py`

    1585
    1586
    1587
    1588
    1589
    1590
    1591

    def __init__(self, identifier=None, members=None, graph=None):
        Class.__init__(self, identifier, graph=graph)
        members = [] if members is None else members
        rdfList = list(  # noqa: N806
            self.graph.objects(predicate=OWL.oneOf, subject=self.identifier)
        )
        OWLRDFListProxy.__init__(self, rdfList, members)

### `` __repr__

    __repr__()

Returns the Manchester Syntax equivalent for this class

Source code in `rdflib/extras/infixowl.py`

    1593
    1594
    1595
    1596
    1597

    def __repr__(self):
        """
        Returns the Manchester Syntax equivalent for this class
        """
        return manchesterSyntax(self._rdfList.uri, self.graph, boolean=self._operator)

### `` isPrimitive

    isPrimitive()

Source code in `rdflib/extras/infixowl.py`

    1582
    1583

    def isPrimitive(self):  # noqa: N802
        return False

### `` serialize

    serialize(graph)

Source code in `rdflib/extras/infixowl.py`

    1599
    1600
    1601
    1602
    1603
    1604
    1605
    1606
    1607
    1608
    1609

    def serialize(self, graph):
        clonedlist = Collection(graph, BNode())
        for cl in self._rdfList:
            clonedlist.append(cl)
            CastClass(cl, self.graph).serialize(graph)

        graph.add((self.identifier, self._operator, clonedlist.uri))
        for s, p, o in self.graph.triples((self.identifier, None, None)):
            if p != self._operator:
                graph.add((s, p, o))
        self._serialize(graph)

## `` Individual

    Individual(identifier=None, graph=None)

A typed individual, the base class of the InfixOWL classes.

Methods:

- `clearInDegree` –

  Remove references to this individual as an object in the

- `clearOutDegree` –

  Remove all statements to this individual as a subject in the

- `delete` –

  Delete the individual from the graph, clearing the in and

- `replace` –

  Replace the individual in the graph with the given other,

- `serialize` –

Attributes:

- `factoryGraph` –
- `graph` –
- `identifier` –
- `qname` –
- `sameAs` –
- `type` –

Source code in `rdflib/extras/infixowl.py`

    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426

    def __init__(self, identifier=None, graph=None):
        self.__identifier = identifier is not None and identifier or BNode()
        if graph is None:
            self.graph = self.factoryGraph
        else:
            self.graph = graph
        self.qname = None
        if not isinstance(self.identifier, BNode):
            try:
                prefix, uri, localname = self.graph.compute_qname(self.identifier)
                self.qname = ":".join([prefix, localname])
            except Exception:  # pragma: no cover
                pass  # pragma: no cover

### `` __identifier `instance-attribute`

    __identifier = identifier is not None and identifier or BNode()

### `` factoryGraph `class-attribute` `instance-attribute`

    factoryGraph = Graph()

### `` graph `instance-attribute`

    graph = factoryGraph

### `` identifier `class-attribute` `instance-attribute`

    identifier = property(_get_identifier, _set_identifier)

### `` qname `instance-attribute`

    qname = join([prefix, localname])

### `` sameAs `class-attribute` `instance-attribute`

    sameAs = property(_get_sameAs, _set_sameAs, _delete_sameAs)

### `` type `class-attribute` `instance-attribute`

    type = property(_get_type, _set_type, _delete_type)

### `` clearInDegree

    clearInDegree()

Remove references to this individual as an object in the backing store.

Source code in `rdflib/extras/infixowl.py`

    428
    429
    430
    431
    432
    433

    def clearInDegree(self):  # noqa: N802
        """
        Remove references to this individual as an object in the
        backing store.
        """
        self.graph.remove((None, None, self.identifier))

### `` clearOutDegree

    clearOutDegree()

Remove all statements to this individual as a subject in the backing store. Note that this only removes the statements themselves, not the blank node closure so there is a chance that this will cause orphaned blank nodes to remain in the graph.

Source code in `rdflib/extras/infixowl.py`

    435
    436
    437
    438
    439
    440
    441
    442
    443

    def clearOutDegree(self):  # noqa: N802
        """
        Remove all statements to this individual as a subject in the
        backing store. Note that this only removes the statements
        themselves, not the blank node closure so there is a chance
        that this will cause orphaned blank nodes to remain in the
        graph.
        """
        self.graph.remove((self.identifier, None, None))

### `` delete

    delete()

Delete the individual from the graph, clearing the in and out degrees.

Source code in `rdflib/extras/infixowl.py`

    445
    446
    447
    448
    449
    450
    451

    def delete(self):
        """
        Delete the individual from the graph, clearing the in and
        out degrees.
        """
        self.clearInDegree()
        self.clearOutDegree()

### `` replace

    replace(other)

Replace the individual in the graph with the given other, causing all triples that refer to it to be changed and then delete the individual.

    >>> g = Graph()
    >>> b = Individual(OWL.Restriction, g)
    >>> b.type = RDFS.Resource
    >>> len(list(b.type))
    1
    >>> del b.type
    >>> len(list(b.type))
    0

Source code in `rdflib/extras/infixowl.py`

    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473

    def replace(self, other):
        """
        Replace the individual in the graph with the given other,
        causing all triples that refer to it to be changed and then
        delete the individual.

        ```python
        >>> g = Graph()
        >>> b = Individual(OWL.Restriction, g)
        >>> b.type = RDFS.Resource
        >>> len(list(b.type))
        1
        >>> del b.type
        >>> len(list(b.type))
        0

        ```
        """
        for s, p, _o in self.graph.triples((None, None, self.identifier)):
            self.graph.add((s, p, classOrIdentifier(other)))
        self.delete()

### `` serialize

    serialize(graph)

Source code in `rdflib/extras/infixowl.py`

    410
    411
    412

    def serialize(self, graph):
        for fact in self.factoryGraph.triples((self.identifier, None, None)):
            graph.add(fact)

## `` Infix

    Infix(function)

Methods:

- `__call__` –
- `__matmul__` –
- `__rlshift__` –
- `__rmatmul__` –
- `__rshift__` –

Attributes:

- `function` –

Source code in `rdflib/extras/infixowl.py`

    222
    223

    def __init__(self, function):
        self.function = function

### `` function `instance-attribute`

    function = function

### `` __call__

    __call__(value1, value2)

Source code in `rdflib/extras/infixowl.py`

    237
    238

    def __call__(self, value1, value2):
        return self.function(value1, value2)  # pragma: no cover

### `` __matmul__

    __matmul__(other)

Source code in `rdflib/extras/infixowl.py`

    234
    235

    def __matmul__(self, other):
        return self.function(other)

### `` __rlshift__

    __rlshift__(other)

Source code in `rdflib/extras/infixowl.py`

    225
    226

    def __rlshift__(self, other):
        return Infix(lambda x, self=self, other=other: self.function(other, x))

### `` __rmatmul__

    __rmatmul__(other)

Source code in `rdflib/extras/infixowl.py`

    231
    232

    def __rmatmul__(self, other):
        return Infix(lambda x, self=self, other=other: self.function(other, x))

### `` __rshift__

    __rshift__(other)

Source code in `rdflib/extras/infixowl.py`

    228
    229

    def __rshift__(self, other):
        return self.function(other)

## `` MalformedClass

Bases: `ValueError`

Deprecated

This class will be removed in version `7.0.0`.

## `` MalformedClassError

    MalformedClassError(msg)

Bases: `MalformedClass`

Methods:

- `__repr__` –

Attributes:

- `msg` –

Source code in `rdflib/extras/infixowl.py`

    987
    988

    def __init__(self, msg):
        self.msg = msg

### `` msg `instance-attribute`

    msg = msg

### `` __repr__

    __repr__()

Source code in `rdflib/extras/infixowl.py`

    990
    991

    def __repr__(self):
        return self.msg

## `` OWLRDFListProxy

    OWLRDFListProxy(rdf_list, members=None, graph=None)

Methods:

- `__contains__` –
- `__delitem__` –
- `__eq__` –

  Equivalence of boolean class constructors is determined by

- `__getitem__` –
- `__iadd__` –
- `__iter__` –
- `__len__` –
- `__setitem__` –
- `append` –
- `clear` –
- `index` –

Attributes:

- `graph` –

Source code in `rdflib/extras/infixowl.py`

    1471
    1472
    1473
    1474
    1475
    1476
    1477
    1478
    1479
    1480
    1481
    1482
    1483
    1484
    1485
    1486

    def __init__(self, rdf_list, members=None, graph=None):
        if graph:
            self.graph = graph
        members = [] if members is None else members
        if rdf_list:
            self._rdfList = Collection(self.graph, rdf_list[0])
            for member in members:
                if member not in self._rdfList:
                    self._rdfList.append(classOrIdentifier(member))
        else:
            self._rdfList = Collection(
                self.graph, BNode(), [classOrIdentifier(m) for m in members]
            )
            # type error: "OWLRDFListProxy" has no attribute "identifier"
            # type error: "OWLRDFListProxy" has no attribute "_operator"
            self.graph.add((self.identifier, self._operator, self._rdfList.uri))  # type: ignore[attr-defined]

### `` graph `instance-attribute`

    graph = graph

### `` __contains__

    __contains__(item)

Source code in `rdflib/extras/infixowl.py`

    1530
    1531
    1532
    1533
    1534

    def __contains__(self, item):
        for i in self._rdfList:
            if i == classOrIdentifier(item):
                return 1
        return 0

### `` __delitem__

    __delitem__(key)

Source code in `rdflib/extras/infixowl.py`

    1520
    1521

    def __delitem__(self, key):
        del self._rdfList[key]

### `` __eq__

    __eq__(other)

Equivalence of boolean class constructors is determined by equivalence of its members

Source code in `rdflib/extras/infixowl.py`

    1488
    1489
    1490
    1491
    1492
    1493
    1494
    1495
    1496
    1497
    1498
    1499
    1500
    1501
    1502
    1503
    1504
    1505

    def __eq__(self, other):
        """
        Equivalence of boolean class constructors is determined by
        equivalence of its members
        """
        assert isinstance(other, Class), repr(other) + repr(type(other))
        if isinstance(other, BooleanClass):
            length = len(self)
            if length != len(other):
                return False
            else:
                for idx in range(length):
                    if self[idx] != other[idx]:
                        return False
                    return True
        else:
            # type error: "OWLRDFListProxy" has no attribute "identifier"
            return self.identifier == other.identifier  # type: ignore[attr-defined]

### `` __getitem__

    __getitem__(key)

Source code in `rdflib/extras/infixowl.py`

    1514
    1515

    def __getitem__(self, key):
        return self._rdfList[key]

### `` __iadd__

    __iadd__(other)

Source code in `rdflib/extras/infixowl.py`

    1539
    1540
    1541

    def __iadd__(self, other):
        self._rdfList.append(classOrIdentifier(other))
        return self

### `` __iter__

    __iter__()

Source code in `rdflib/extras/infixowl.py`

    1526
    1527
    1528

    def __iter__(self):
        for item in self._rdfList:
            yield item

### `` __len__

    __len__()

Source code in `rdflib/extras/infixowl.py`

    1508
    1509

    def __len__(self):
        return len(self._rdfList)

### `` __setitem__

    __setitem__(key, value)

Source code in `rdflib/extras/infixowl.py`

    1517
    1518

    def __setitem__(self, key, value):
        self._rdfList[key] = classOrIdentifier(value)

### `` append

    append(item)

Source code in `rdflib/extras/infixowl.py`

    1536
    1537

    def append(self, item):
        self._rdfList.append(item)

### `` clear

    clear()

Source code in `rdflib/extras/infixowl.py`

    1523
    1524

    def clear(self):
        self._rdfList.clear()

### `` index

    index(item)

Source code in `rdflib/extras/infixowl.py`

    1511
    1512

    def index(self, item):
        return self._rdfList.index(classOrIdentifier(item))

## `` Ontology

    Ontology(identifier=None, imports=None, comment=None, graph=None)

Bases: `AnnotatableTerms`

The owl ontology metadata

Methods:

- `setVersion` –

Attributes:

- `comment` –
- `imports` –

Source code in `rdflib/extras/infixowl.py`

    762
    763
    764
    765
    766
    767

    def __init__(self, identifier=None, imports=None, comment=None, graph=None):
        super(Ontology, self).__init__(identifier, graph)
        self.imports = [] if imports is None else imports
        self.comment = [] if comment is None else comment
        if (self.identifier, RDF.type, OWL.Ontology) not in self.graph:
            self.graph.add((self.identifier, RDF.type, OWL.Ontology))

### `` comment `instance-attribute`

    comment = [] if comment is None else comment

### `` imports `class-attribute` `instance-attribute`

    imports = property(_get_imports, _set_imports, _del_imports)

### `` setVersion

    setVersion(version)

Source code in `rdflib/extras/infixowl.py`

    769
    770

    def setVersion(self, version):  # noqa: N802
        self.graph.set((self.identifier, OWL.versionInfo, version))

## `` Property

    Property(identifier=None, graph=None, baseType=ObjectProperty, subPropertyOf=None, domain=None, range=None, inverseOf=None, otherType=None, equivalentProperty=None, comment=None, verbAnnotations=None, nameAnnotation=None, nameIsLabel=False)

Bases: `AnnotatableTerms`

    axiom ::= 'DatatypeProperty(' datavaluedPropertyID ['Deprecated']
                { annotation }
                { 'super(' datavaluedPropertyID ')'} ['Functional']
                { 'domain(' description ')' } { 'range(' dataRange ')' } ')'
                | 'ObjectProperty(' individualvaluedPropertyID ['Deprecated']
                { annotation }
                { 'super(' individualvaluedPropertyID ')' }
                [ 'inverseOf(' individualvaluedPropertyID ')' ] [ 'Symmetric' ]
                [ 'Functional' | 'InverseFunctional' |
                'Functional' 'InverseFunctional' |
                'Transitive' ]
                { 'domain(' description ')' } { 'range(' description ')' } ')

Methods:

- `__repr__` –
- `replace` –
- `serialize` –
- `setupVerbAnnotations` –

  OWL properties map to ACE transitive verbs (TV)

Attributes:

- `comment` –
- `domain` –
- `extent` –
- `inverseOf` –
- `range` –
- `subPropertyOf` –

Source code in `rdflib/extras/infixowl.py`

    2168
    2169
    2170
    2171
    2172
    2173
    2174
    2175
    2176
    2177
    2178
    2179
    2180
    2181
    2182
    2183
    2184
    2185
    2186
    2187
    2188
    2189
    2190
    2191
    2192
    2193
    2194
    2195
    2196
    2197
    2198
    2199
    2200

    def __init__(
        self,
        identifier=None,
        graph=None,
        baseType=OWL.ObjectProperty,  # noqa: N803
        subPropertyOf=None,  # noqa: N803
        domain=None,
        range=None,
        inverseOf=None,  # noqa: N803
        otherType=None,  # noqa: N803
        equivalentProperty=None,  # noqa: N803
        comment=None,
        verbAnnotations=None,  # noqa: N803
        nameAnnotation=None,  # noqa: N803
        nameIsLabel=False,  # noqa: N803
    ):
        super(Property, self).__init__(identifier, graph, nameAnnotation, nameIsLabel)
        if verbAnnotations:
            self.setupVerbAnnotations(verbAnnotations)

        assert not isinstance(self.identifier, BNode)
        if baseType is None:
            # None give, determine via introspection
            self._baseType = first(Individual(self.identifier, graph=self.graph).type)
        else:
            if (self.identifier, RDF.type, baseType) not in self.graph:
                self.graph.add((self.identifier, RDF.type, baseType))
            self._baseType = baseType
        self.subPropertyOf = subPropertyOf
        self.inverseOf = inverseOf
        self.domain = domain
        self.range = range
        self.comment = [] if comment is None else comment

### `` comment `instance-attribute`

    comment = [] if comment is None else comment

### `` domain `class-attribute` `instance-attribute`

    domain = property(_get_domain, _set_domain, _del_domain)

### `` extent `class-attribute` `instance-attribute`

    extent = property(_get_extent, _set_extent)

### `` inverseOf `class-attribute` `instance-attribute`

    inverseOf = property(_get_inverseof, _set_inverseof, _del_inverseof)

### `` range `class-attribute` `instance-attribute`

    range = property(_get_range, _set_range, _del_range)

### `` subPropertyOf `class-attribute` `instance-attribute`

    subPropertyOf = property(_get_subpropertyof, _set_subpropertyof, _del_subpropertyof)

### `` __repr__

    __repr__()

Source code in `rdflib/extras/infixowl.py`

    2224
    2225
    2226
    2227
    2228
    2229
    2230
    2231
    2232
    2233
    2234
    2235
    2236
    2237
    2238
    2239
    2240
    2241
    2242
    2243
    2244
    2245
    2246
    2247
    2248
    2249
    2250
    2251
    2252
    2253
    2254
    2255
    2256
    2257
    2258
    2259
    2260
    2261
    2262
    2263
    2264
    2265
    2266
    2267
    2268
    2269
    2270
    2271
    2272
    2273
    2274
    2275
    2276
    2277
    2278
    2279
    2280
    2281
    2282
    2283
    2284
    2285
    2286
    2287
    2288
    2289
    2290
    2291
    2292
    2293
    2294
    2295
    2296
    2297
    2298
    2299
    2300
    2301
    2302
    2303
    2304
    2305
    2306
    2307
    2308
    2309
    2310
    2311
    2312

    def __repr__(self):
        rt = []
        if OWL.ObjectProperty in self.type:
            rt.append(
                "ObjectProperty( %s annotation(%s)"
                % (self.qname, first(self.comment) and first(self.comment) or "")
            )
            if first(self.inverseOf):
                # type error: Item "None" of "Optional[Any]" has no attribute "inverseOf"
                two_link_inverse = first(first(self.inverseOf).inverseOf)  # type: ignore[union-attr]
                if two_link_inverse and two_link_inverse.identifier == self.identifier:
                    # type error: Item "None" of "Optional[Any]" has no attribute "qname"
                    inverserepr = first(self.inverseOf).qname  # type: ignore[union-attr]
                else:
                    inverserepr = repr(first(self.inverseOf))
                rt.append(
                    "  inverseOf( %s )%s"
                    % (
                        inverserepr,
                        OWL.SymmetricProperty in self.type and " Symmetric" or "",
                    )
                )
            for _s, _p, roletype in self.graph.triples_choices(
                # type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, URIRef, List[URIRef]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
                (  # type: ignore[arg-type]
                    self.identifier,
                    RDF.type,
                    [
                        OWL.FunctionalProperty,
                        OWL.InverseFunctionalProperty,
                        OWL.TransitiveProperty,
                    ],
                )
            ):
                # type error: "Node" has no attribute "split"
                rt.append(str(roletype.split(str(OWL))[-1]))  # type: ignore[attr-defined]
        else:
            rt.append(
                "DatatypeProperty( %s %s"
                % (self.qname, first(self.comment) and first(self.comment) or "")
            )
            for _s, _p, roletype in self.graph.triples(
                (self.identifier, RDF.type, OWL.FunctionalProperty)
            ):
                rt.append("   Functional")

        def canonicalName(term, g):  # noqa: N802
            normalized_name = classOrIdentifier(term)
            if isinstance(normalized_name, BNode):
                return term
            elif normalized_name.startswith(XSD):
                return str(term)
            elif first(
                g.triples_choices(
                    (normalized_name, [OWL.unionOf, OWL.intersectionOf], None)
                )
            ):
                return repr(term)
            else:
                return str(term.qname)

        rt.append(
            " ".join(
                [
                    "   super( %s )" % canonicalName(super_property, self.graph)
                    for super_property in self.subPropertyOf
                ]
            )
        )
        rt.append(
            " ".join(
                [
                    "   domain( %s )" % canonicalName(domain, self.graph)
                    for domain in self.domain
                ]
            )
        )
        rt.append(
            " ".join(
                [
                    "   range( %s )" % canonicalName(range, self.graph)
                    for range in self.range
                ]
            )
        )
        # type error: Incompatible types in assignment (expression has type "str", variable has type "List[str]")
        rt = "\n".join([expr for expr in rt if expr])  # type: ignore[assignment]
        rt += "\n)"
        return rt

### `` replace

    replace(other)

Source code in `rdflib/extras/infixowl.py`

    2389
    2390
    2391
    2392
    2393

    def replace(self, other):
        # extension = []
        for s, _p, o in self.extent:
            self.graph.add((s, propertyOrIdentifier(other), o))
        self.graph.remove((None, self.identifier, None))

### `` serialize

    serialize(graph)

Source code in `rdflib/extras/infixowl.py`

    2202
    2203
    2204
    2205
    2206
    2207
    2208

    def serialize(self, graph):
        for fact in self.graph.triples((self.identifier, None, None)):
            graph.add(fact)
        for p in itertools.chain(self.subPropertyOf, self.inverseOf):
            p.serialize(graph)
        for c in itertools.chain(self.domain, self.range):
            CastClass(c, self.graph).serialize(graph)

### `` setupVerbAnnotations

    setupVerbAnnotations(verb_annotations)

OWL properties map to ACE transitive verbs (TV)

There are 6 morphological categories that determine the surface form of an IRI:

- singular form of a transitive verb (e.g. mans)
- plural form of a transitive verb (e.g. man)
- past participle form a transitive verb (e.g. manned)
- http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg
- http://attempto.ifi.uzh.ch/ace_lexicon#TV_pl
- http://attempto.ifi.uzh.ch/ace_lexicon#TV_vbg

Source code in `rdflib/extras/infixowl.py`

    2137
    2138
    2139
    2140
    2141
    2142
    2143
    2144
    2145
    2146
    2147
    2148
    2149
    2150
    2151
    2152
    2153
    2154
    2155
    2156
    2157
    2158
    2159
    2160
    2161
    2162
    2163
    2164
    2165
    2166

    def setupVerbAnnotations(self, verb_annotations):  # noqa: N802
        """OWL properties map to ACE transitive verbs (TV)

        There are 6 morphological categories that determine the surface form
        of an IRI:

        - singular form of a transitive verb (e.g. mans)
        - plural form of a transitive verb (e.g. man)
        - past participle form a transitive verb (e.g. manned)
        - http://attempto.ifi.uzh.ch/ace_lexicon#TV_sg
        - http://attempto.ifi.uzh.ch/ace_lexicon#TV_pl
        - http://attempto.ifi.uzh.ch/ace_lexicon#TV_vbg
        """

        if isinstance(verb_annotations, tuple):
            tv_sgprop, tv_plprop, tv_vbg = verb_annotations
        else:
            tv_sgprop = verb_annotations
            tv_plprop = verb_annotations
            tv_vbg = verb_annotations
        if tv_sgprop:
            self.tv_sgprop.extent = [
                (self.identifier, self.handleAnnotation(tv_sgprop))
            ]
        if tv_plprop:
            self.tv_plprop.extent = [
                (self.identifier, self.handleAnnotation(tv_plprop))
            ]
        if tv_vbg:
            self.tv_vbgprop.extent = [(self.identifier, self.handleAnnotation(tv_vbg))]

## `` Restriction

    Restriction(onProperty, graph=None, allValuesFrom=None, someValuesFrom=None, value=None, cardinality=None, maxCardinality=None, minCardinality=None, identifier=None)

Bases: `Class`

    restriction ::= 'restriction('
    datavaluedPropertyID dataRestrictionComponent
    { dataRestrictionComponent } ')'
    | 'restriction(' individualvaluedPropertyID
    individualRestrictionComponent
    { individualRestrictionComponent } ')'

Methods:

- `__eq__` –

  Equivalence of restrictions is determined by equivalence of the

- `__hash__` –
- `__repr__` –

  Returns the Manchester Syntax equivalent for this restriction

- `isPrimitive` –
- `restrictionKind` –
- `serialize` –

  ```python

Attributes:

- `allValuesFrom` –
- `cardinality` –
- `hasValue` –
- `maxCardinality` –
- `minCardinality` –
- `onProperty` –
- `restrictionKinds` –
- `restrictionRange` –
- `restrictionType` –
- `someValuesFrom` –

Source code in `rdflib/extras/infixowl.py`

    1802
    1803
    1804
    1805
    1806
    1807
    1808
    1809
    1810
    1811
    1812
    1813
    1814
    1815
    1816
    1817
    1818
    1819
    1820
    1821
    1822
    1823
    1824
    1825
    1826
    1827
    1828
    1829
    1830
    1831
    1832
    1833
    1834
    1835
    1836
    1837
    1838
    1839
    1840
    1841
    1842
    1843
    1844
    1845
    1846
    1847
    1848
    1849
    1850
    1851
    1852
    1853
    1854
    1855
    1856
    1857
    1858
    1859
    1860
    1861
    1862
    1863

    def __init__(
        self,
        onProperty,  # noqa: N803
        graph=None,
        allValuesFrom=None,  # noqa: N803
        someValuesFrom=None,  # noqa: N803
        value=None,
        cardinality=None,
        maxCardinality=None,  # noqa: N803
        minCardinality=None,  # noqa: N803
        identifier=None,
    ):
        graph = Graph() if graph is None else graph
        super(Restriction, self).__init__(
            identifier, graph=graph, skipOWLClassMembership=True
        )
        if (
            self.identifier,
            OWL.onProperty,
            propertyOrIdentifier(onProperty),
        ) not in graph:
            graph.add(
                (self.identifier, OWL.onProperty, propertyOrIdentifier(onProperty))
            )
        self.onProperty = onProperty
        restr_types = [
            (allValuesFrom, OWL.allValuesFrom),
            (someValuesFrom, OWL.someValuesFrom),
            (value, OWL.hasValue),
            (cardinality, OWL.cardinality),
            (maxCardinality, OWL.maxCardinality),
            (minCardinality, OWL.minCardinality),
        ]
        valid_restr_props = [(i, oterm) for (i, oterm) in restr_types if i is not None]
        if not len(valid_restr_props):
            raise ValueError(
                "Missing value. One of: allValuesFrom, someValuesFrom,"
                "value, cardinality, maxCardinality or minCardinality"
                "must have a value."
            )
        restriction_range, restriction_type = valid_restr_props.pop()
        self.restrictionType = restriction_type
        if isinstance(restriction_range, Identifier):
            self.restrictionRange = restriction_range
        elif isinstance(restriction_range, Class):
            self.restrictionRange = classOrIdentifier(restriction_range)
        else:
            # error: Incompatible types in assignment (expression has type "Optional[Identifier]", variable has type "Identifier")
            self.restrictionRange = first(  # type: ignore[assignment]
                # type error: Argument 1 to "first" has incompatible type "Generator[Node, None, None]"; expected "Iterable[Identifier]"
                self.graph.objects(self.identifier, restriction_type)  # type: ignore[arg-type]
            )
        if (
            self.identifier,
            restriction_type,
            self.restrictionRange,
        ) not in self.graph:
            self.graph.add((self.identifier, restriction_type, self.restrictionRange))
        assert self.restrictionRange is not None, Class(self.identifier)
        if (self.identifier, RDF.type, OWL.Restriction) not in self.graph:
            self.graph.add((self.identifier, RDF.type, OWL.Restriction))
            self.graph.remove((self.identifier, RDF.type, OWL.Class))

### `` allValuesFrom `class-attribute` `instance-attribute`

    allValuesFrom = property(_get_allvaluesfrom, _set_allvaluesfrom, _del_allvaluesfrom)

### `` cardinality `class-attribute` `instance-attribute`

    cardinality = property(_get_cardinality, _set_cardinality, _del_cardinality)

### `` hasValue `class-attribute` `instance-attribute`

    hasValue = property(_get_hasvalue, _set_hasvalue, _del_hasvalue)

### `` maxCardinality `class-attribute` `instance-attribute`

    maxCardinality = property(_get_maxcardinality, _set_maxcardinality, _del_maxcardinality)

### `` minCardinality `class-attribute` `instance-attribute`

    minCardinality = property(_get_mincardinality, _set_mincardinality, _del_mincardinality)

### `` onProperty `class-attribute` `instance-attribute`

    onProperty = property(_get_onproperty, _set_onproperty, _del_onproperty)

### `` restrictionKinds `class-attribute` `instance-attribute`

    restrictionKinds = [allValuesFrom, someValuesFrom, hasValue, cardinality, maxCardinality, minCardinality]

### `` restrictionRange `instance-attribute`

    restrictionRange = restriction_range

### `` restrictionType `instance-attribute`

    restrictionType = restriction_type

### `` someValuesFrom `class-attribute` `instance-attribute`

    someValuesFrom = property(_get_somevaluesfrom, _set_somevaluesfrom, _del_somevaluesfrom)

### `` __eq__

    __eq__(other)

Equivalence of restrictions is determined by equivalence of the property in question and the restriction ‘range’

Source code in `rdflib/extras/infixowl.py`

    1902
    1903
    1904
    1905
    1906
    1907
    1908
    1909
    1910
    1911
    1912
    1913
    1914
    1915

    def __eq__(self, other):
        """
        Equivalence of restrictions is determined by equivalence of the
        property in question and the restriction 'range'
        """
        assert isinstance(other, Class), repr(other) + repr(type(other))
        if isinstance(other, Restriction):
            return (
                other.onProperty == self.onProperty
                # type error: "Restriction" has no attribute "restriction_range"; maybe "restrictionRange"?
                and other.restriction_range == self.restrictionRange  # type: ignore[attr-defined]
            )
        else:
            return False

### `` __hash__

    __hash__()

Source code in `rdflib/extras/infixowl.py`

    1899
    1900

    def __hash__(self):
        return hash((self.onProperty, self.restrictionRange))

### `` __repr__

    __repr__()

Returns the Manchester Syntax equivalent for this restriction

Source code in `rdflib/extras/infixowl.py`

    2084
    2085
    2086
    2087
    2088

    def __repr__(self):
        """
        Returns the Manchester Syntax equivalent for this restriction
        """
        return manchesterSyntax(self.identifier, self.graph)

### `` isPrimitive

    isPrimitive()

Source code in `rdflib/extras/infixowl.py`

    1896
    1897

    def isPrimitive(self):  # noqa: N802
        return False

### `` restrictionKind

    restrictionKind()

Source code in `rdflib/extras/infixowl.py`

    2075
    2076
    2077
    2078
    2079
    2080
    2081
    2082

    def restrictionKind(self):  # noqa: N802
        for s, p, o in self.graph.triples_choices(
            # type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, List[URIRef], None]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
            (self.identifier, self.restrictionKinds, None)  # type: ignore[arg-type]
        ):
            # type error: "Node" has no attribute "split"
            return p.split(str(OWL))[-1]  # type: ignore[attr-defined]
        return None

### `` serialize

    serialize(graph)

    >>> g1 = Graph()
    >>> g2 = Graph()
    >>> EX = Namespace("http://example.com/")
    >>> g1.bind("ex", EX, override=False)
    >>> g2.bind("ex", EX, override=False)
    >>> Individual.factoryGraph = g1
    >>> prop = Property(EX.someProp, baseType=OWL.DatatypeProperty)
    >>> restr1 = (Property(
    ...    EX.someProp,
    ...    baseType=OWL.DatatypeProperty)) @ some @ (Class(EX.Foo))
    >>> restr1  # doctest: +SKIP
    ( ex:someProp SOME ex:Foo )
    >>> restr1.serialize(g2)
    >>> Individual.factoryGraph = g2
    >>> list(Property(
    ...     EX.someProp,baseType=None).type
    ... ) #doctest: +NORMALIZE_WHITESPACE +SKIP
    [rdflib.term.URIRef(
        'http://www.w3.org/2002/07/owl#DatatypeProperty')]

Source code in `rdflib/extras/infixowl.py`

    1865
    1866
    1867
    1868
    1869
    1870
    1871
    1872
    1873
    1874
    1875
    1876
    1877
    1878
    1879
    1880
    1881
    1882
    1883
    1884
    1885
    1886
    1887
    1888
    1889
    1890
    1891
    1892
    1893
    1894

    def serialize(self, graph):
        """
        ```python
        >>> g1 = Graph()
        >>> g2 = Graph()
        >>> EX = Namespace("http://example.com/")
        >>> g1.bind("ex", EX, override=False)
        >>> g2.bind("ex", EX, override=False)
        >>> Individual.factoryGraph = g1
        >>> prop = Property(EX.someProp, baseType=OWL.DatatypeProperty)
        >>> restr1 = (Property(
        ...    EX.someProp,
        ...    baseType=OWL.DatatypeProperty)) @ some @ (Class(EX.Foo))
        >>> restr1  # doctest: +SKIP
        ( ex:someProp SOME ex:Foo )
        >>> restr1.serialize(g2)
        >>> Individual.factoryGraph = g2
        >>> list(Property(
        ...     EX.someProp,baseType=None).type
        ... ) #doctest: +NORMALIZE_WHITESPACE +SKIP
        [rdflib.term.URIRef(
            'http://www.w3.org/2002/07/owl#DatatypeProperty')]

        ```
        """
        Property(self.onProperty, graph=self.graph, baseType=None).serialize(graph)
        for s, p, o in self.graph.triples((self.identifier, None, None)):
            graph.add((s, p, o))
            if p in [OWL.allValuesFrom, OWL.someValuesFrom]:
                CastClass(o, self.graph).serialize(graph)

## `` TermDeletionHelper

    TermDeletionHelper(prop)

Methods:

- `__call__` –

Attributes:

- `prop` –

Source code in `rdflib/extras/infixowl.py`

    393
    394

    def __init__(self, prop):
        self.prop = prop

### `` prop `instance-attribute`

    prop = prop

### `` __call__

    __call__(f)

Source code in `rdflib/extras/infixowl.py`

    396
    397
    398
    399
    400

    def __call__(self, f):
        def _remover(inst):
            inst.graph.remove((inst.identifier, self.prop, None))

        return _remover

## `` AllClasses

    AllClasses(graph)

Source code in `rdflib/extras/infixowl.py`

    791
    792
    793

    def AllClasses(graph):  # noqa: N802
        for c in set(graph.subjects(predicate=RDF.type, object=OWL.Class)):
            yield Class(c)

## `` AllDifferent

    AllDifferent(members)

TODO: implement this function

DisjointClasses(’ description description { description } ‘)’

Source code in `rdflib/extras/infixowl.py`

    1772
    1773
    1774
    1775
    1776
    1777
    1778

    def AllDifferent(members):  # noqa: N802
        """
        TODO: implement this function

        DisjointClasses(' description description { description } ')'
        """
        pass  # pragma: no cover

## `` AllProperties

    AllProperties(graph)

Source code in `rdflib/extras/infixowl.py`

    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824

    def AllProperties(graph):  # noqa: N802
        prevprops = set()
        for s, _p, o in graph.triples_choices(
            (
                None,
                RDF.type,
                [
                    OWL.SymmetricProperty,
                    OWL.FunctionalProperty,
                    OWL.InverseFunctionalProperty,
                    OWL.TransitiveProperty,
                    OWL.DatatypeProperty,
                    OWL.ObjectProperty,
                    OWL.AnnotationProperty,
                ],
            )
        ):
            if o in [
                OWL.SymmetricProperty,
                OWL.InverseFunctionalProperty,
                OWL.TransitiveProperty,
                OWL.ObjectProperty,
            ]:
                bType = OWL.ObjectProperty  # noqa: N806
            else:
                bType = OWL.DatatypeProperty  # noqa: N806
            if s not in prevprops:
                prevprops.add(s)
                yield Property(s, graph=graph, baseType=bType)

## `` CastClass

    CastClass(c, graph=None)

Source code in `rdflib/extras/infixowl.py`

     994
     995
     996
     997
     998
     999
    1000
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025

    def CastClass(c, graph=None):  # noqa: N802
        graph = graph is None and c.factoryGraph or graph
        for kind in graph.objects(subject=classOrIdentifier(c), predicate=RDF.type):
            if kind == OWL.Restriction:
                kwargs = {"identifier": classOrIdentifier(c), "graph": graph}
                for _s, p, o in graph.triples((classOrIdentifier(c), None, None)):
                    if p != RDF.type:
                        if p == OWL.onProperty:
                            kwargs["onProperty"] = o
                        else:
                            if p not in Restriction.restrictionKinds:
                                continue
                            kwargs[str(p.split(str(OWL))[-1])] = o
                if not set(
                    [str(i.split(str(OWL))[-1]) for i in Restriction.restrictionKinds]
                ).intersection(kwargs):
                    raise MalformedClassError("Malformed owl:Restriction")
                return Restriction(**kwargs)
            else:
                for _s, p, _o in graph.triples_choices(
                    (
                        classOrIdentifier(c),
                        [OWL.intersectionOf, OWL.unionOf, OWL.oneOf],
                        None,
                    )
                ):
                    if p == OWL.oneOf:
                        return EnumeratedClass(classOrIdentifier(c), graph=graph)
                    else:
                        return BooleanClass(classOrIdentifier(c), operator=p, graph=graph)
                # assert (classOrIdentifier(c),RDF.type,OWL.Class) in graph
                return Class(classOrIdentifier(c), graph=graph, skipOWLClassMembership=True)

## `` CommonNSBindings

    CommonNSBindings(graph, additionalNS=None)

Takes a graph and binds the common namespaces (rdf,rdfs, & owl)

Source code in `rdflib/extras/infixowl.py`

    2396
    2397
    2398
    2399
    2400
    2401
    2402
    2403
    2404
    2405
    2406
    2407

    def CommonNSBindings(graph, additionalNS=None):  # noqa: N802, N803
        """
        Takes a graph and binds the common namespaces (rdf,rdfs, & owl)
        """
        additional_ns = {} if additionalNS is None else additionalNS
        namespace_manager = NamespaceManager(graph)
        namespace_manager.bind("rdfs", RDFS)
        namespace_manager.bind("rdf", RDF)
        namespace_manager.bind("owl", OWL)
        for prefix, uri in list(additional_ns.items()):
            namespace_manager.bind(prefix, uri, override=False)
        graph.namespace_manager = namespace_manager

## `` ComponentTerms

    ComponentTerms(cls)

Takes a Class instance and returns a generator over the classes that are involved in its definition, ignoring unnamed classes

Source code in `rdflib/extras/infixowl.py`

    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    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 ComponentTerms(cls):  # noqa: N802
        """
        Takes a Class instance and returns a generator over the classes that
        are involved in its definition, ignoring unnamed classes
        """
        if OWL.Restriction in cls.type:
            try:
                cls = CastClass(cls, Individual.factoryGraph)
                for _s, _p, inner_class_id in cls.factoryGraph.triples_choices(
                    (cls.identifier, [OWL.allValuesFrom, OWL.someValuesFrom], None)
                ):
                    inner_class = Class(inner_class_id, skipOWLClassMembership=True)
                    if isinstance(inner_class_id, BNode):
                        for _c in ComponentTerms(inner_class):
                            yield _c
                    else:
                        yield inner_class
            except Exception:  # pragma: no cover
                pass  # pragma: no cover
        else:
            cls = CastClass(cls, Individual.factoryGraph)
            if isinstance(cls, BooleanClass):
                for _cls in cls:
                    _cls = Class(_cls, skipOWLClassMembership=True)
                    if isinstance(_cls.identifier, BNode):
                        for _c in ComponentTerms(_cls):
                            yield _c
                    else:
                        yield _cls
            else:
                for inner_class in cls.subClassOf:
                    if isinstance(inner_class.identifier, BNode):
                        for _c in ComponentTerms(inner_class):
                            yield _c
                    else:
                        yield inner_class
                for _s, _p, o in cls.factoryGraph.triples_choices(
                    (classOrIdentifier(cls), CLASS_RELATIONS, None)
                ):
                    if isinstance(o, BNode):
                        for _c in ComponentTerms(CastClass(o, Individual.factoryGraph)):
                            yield _c
                    else:
                        yield inner_class

## `` DeepClassClear

    DeepClassClear(class_to_prune)

Recursively clear the given class, continuing where any related class is an anonymous class

    >>> EX = Namespace("http://example.com/")
    >>> g = Graph()
    >>> g.bind("ex", EX, override=False)
    >>> Individual.factoryGraph = g
    >>> classB = Class(EX.B)
    >>> classC = Class(EX.C)
    >>> classD = Class(EX.D)
    >>> classE = Class(EX.E)
    >>> classF = Class(EX.F)
    >>> anonClass = EX.someProp @ some @ classD
    >>> classF += anonClass
    >>> list(anonClass.subClassOf)
    [Class: ex:F ]
    >>> classA = classE | classF | anonClass
    >>> classB += classA
    >>> classA.equivalentClass = [Class()]
    >>> classB.subClassOf = [EX.someProp @ some @ classC]
    >>> classA
    ( ex:E OR ex:F OR ( ex:someProp SOME ex:D ) )
    >>> DeepClassClear(classA)
    >>> classA
    (  )
    >>> list(anonClass.subClassOf)
    []
    >>> classB
    Class: ex:B SubClassOf: ( ex:someProp SOME ex:C )

    >>> otherClass = classD | anonClass
    >>> otherClass
    ( ex:D OR ( ex:someProp SOME ex:D ) )
    >>> DeepClassClear(otherClass)
    >>> otherClass
    (  )
    >>> otherClass.delete()
    >>> list(g.triples((otherClass.identifier, None, None)))
    []

Source code in `rdflib/extras/infixowl.py`

    907
    908
    909
    910
    911
    912
    913
    914
    915
    916
    917
    918
    919
    920
    921
    922
    923
    924
    925
    926
    927
    928
    929
    930
    931
    932
    933
    934
    935
    936
    937
    938
    939
    940
    941
    942
    943
    944
    945
    946
    947
    948
    949
    950
    951
    952
    953
    954
    955
    956
    957
    958
    959
    960
    961
    962
    963
    964
    965
    966
    967
    968
    969
    970
    971
    972
    973
    974

    def DeepClassClear(class_to_prune):  # noqa: N802
        """
        Recursively clear the given class, continuing
        where any related class is an anonymous class

        ```python
        >>> EX = Namespace("http://example.com/")
        >>> g = Graph()
        >>> g.bind("ex", EX, override=False)
        >>> Individual.factoryGraph = g
        >>> classB = Class(EX.B)
        >>> classC = Class(EX.C)
        >>> classD = Class(EX.D)
        >>> classE = Class(EX.E)
        >>> classF = Class(EX.F)
        >>> anonClass = EX.someProp @ some @ classD
        >>> classF += anonClass
        >>> list(anonClass.subClassOf)
        [Class: ex:F ]
        >>> classA = classE | classF | anonClass
        >>> classB += classA
        >>> classA.equivalentClass = [Class()]
        >>> classB.subClassOf = [EX.someProp @ some @ classC]
        >>> classA
        ( ex:E OR ex:F OR ( ex:someProp SOME ex:D ) )
        >>> DeepClassClear(classA)
        >>> classA
        (  )
        >>> list(anonClass.subClassOf)
        []
        >>> classB
        Class: ex:B SubClassOf: ( ex:someProp SOME ex:C )

        >>> otherClass = classD | anonClass
        >>> otherClass
        ( ex:D OR ( ex:someProp SOME ex:D ) )
        >>> DeepClassClear(otherClass)
        >>> otherClass
        (  )
        >>> otherClass.delete()
        >>> list(g.triples((otherClass.identifier, None, None)))
        []

        ```
        """

        def deepClearIfBNode(_class):  # noqa: N802
            if isinstance(classOrIdentifier(_class), BNode):
                DeepClassClear(_class)

        class_to_prune = CastClass(class_to_prune, Individual.factoryGraph)
        for c in class_to_prune.subClassOf:
            deepClearIfBNode(c)
        class_to_prune.graph.remove((class_to_prune.identifier, RDFS.subClassOf, None))
        for c in class_to_prune.equivalentClass:
            deepClearIfBNode(c)
        class_to_prune.graph.remove((class_to_prune.identifier, OWL.equivalentClass, None))
        inverse_class = class_to_prune.complementOf
        if inverse_class:
            class_to_prune.graph.remove((class_to_prune.identifier, OWL.complementOf, None))
            deepClearIfBNode(inverse_class)
        if isinstance(class_to_prune, BooleanClass):
            for c in class_to_prune:
                deepClearIfBNode(c)
            class_to_prune.clear()
            class_to_prune.graph.remove(
                (class_to_prune.identifier, class_to_prune._operator, None)
            )

## `` GetIdentifiedClasses

    GetIdentifiedClasses(graph)

Source code in `rdflib/extras/infixowl.py`

    386
    387
    388
    389

    def GetIdentifiedClasses(graph):  # noqa: N802
        for c in graph.subjects(predicate=RDF.type, object=OWL.Class):
            if isinstance(c, URIRef):
                yield Class(c)

## `` classOrIdentifier

    classOrIdentifier(thing)

Source code in `rdflib/extras/infixowl.py`

    264
    265
    266
    267
    268
    269
    270
    271

    def classOrIdentifier(thing):  # noqa: N802
        if isinstance(thing, (Property, Class)):
            return thing.identifier
        else:
            assert isinstance(thing, (URIRef, BNode)), (
                "Expecting a Class, Property, URIRef, or BNode.. not a %s" % thing
            )
            return thing

## `` classOrTerm

    classOrTerm(thing)

Source code in `rdflib/extras/infixowl.py`

    256
    257
    258
    259
    260
    261

    def classOrTerm(thing):  # noqa: N802
        if isinstance(thing, Class):
            return thing.identifier
        else:
            assert isinstance(thing, (URIRef, BNode, Literal))
            return thing

## `` generateQName

    generateQName(graph, uri)

Source code in `rdflib/extras/infixowl.py`

    251
    252
    253

    def generateQName(graph, uri):  # noqa: N802
        prefix, uri, localname = graph.compute_qname(classOrIdentifier(uri))
        return ":".join([prefix, localname])

## `` manchesterSyntax

    manchesterSyntax(thing, store, boolean=None, transientList=False)

Core serialization thing is a Class and is processed as a subject store is an RDFLib Graph to be queried about thing

Source code in `rdflib/extras/infixowl.py`

    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

    def manchesterSyntax(  # noqa: N802
        thing, store, boolean=None, transientList=False  # noqa: N803
    ):
        """
        Core serialization
        thing is a Class and is processed as a subject
        store is an RDFLib Graph to be queried about thing
        """
        assert thing is not None
        if boolean:
            if transientList:
                livechildren = iter(thing)
                children = [manchesterSyntax(child, store) for child in thing]
            else:
                livechildren = iter(Collection(store, thing))
                children = [
                    manchesterSyntax(child, store) for child in Collection(store, thing)
                ]
            if boolean == OWL.intersectionOf:
                childlist = []
                named = []
                for child in livechildren:
                    if isinstance(child, URIRef):
                        named.append(child)
                    else:
                        childlist.append(child)
                if named:

                    def castToQName(x):  # noqa: N802
                        prefix, uri, localname = store.compute_qname(x)
                        return ":".join([prefix, localname])

                    if len(named) > 1:
                        prefix = "( " + " AND ".join(map(castToQName, named)) + " )"
                    else:
                        prefix = manchesterSyntax(named[0], store)
                    if childlist:
                        return (
                            str(prefix)
                            + " THAT "
                            + " AND ".join(
                                [str(manchesterSyntax(x, store)) for x in childlist]
                            )
                        )
                    else:
                        return prefix
                else:
                    return "( " + " AND ".join([str(c) for c in children]) + " )"
            elif boolean == OWL.unionOf:
                return "( " + " OR ".join([str(c) for c in children]) + " )"
            elif boolean == OWL.oneOf:
                return "{ " + " ".join([str(c) for c in children]) + " }"
            else:
                assert boolean == OWL.complementOf
        elif OWL.Restriction in store.objects(subject=thing, predicate=RDF.type):
            prop = list(store.objects(subject=thing, predicate=OWL.onProperty))[0]
            prefix, uri, localname = store.compute_qname(prop)
            propstring = ":".join([prefix, localname])
            label = first(store.objects(subject=prop, predicate=RDFS.label))
            if label:
                propstring = "'%s'" % label
            for onlyclass in store.objects(subject=thing, predicate=OWL.allValuesFrom):
                return "( %s ONLY %s )" % (propstring, manchesterSyntax(onlyclass, store))
            for val in store.objects(subject=thing, predicate=OWL.hasValue):
                return "( %s VALUE %s )" % (propstring, manchesterSyntax(val, store))
            for someclass in store.objects(subject=thing, predicate=OWL.someValuesFrom):
                return "( %s SOME %s )" % (propstring, manchesterSyntax(someclass, store))
            cardlookup = {
                OWL.maxCardinality: "MAX",
                OWL.minCardinality: "MIN",
                OWL.cardinality: "EQUALS",
            }
            for _s, p, o in store.triples_choices((thing, list(cardlookup.keys()), None)):
                return "( %s %s %s )" % (propstring, cardlookup[p], o)
        # is thing a complement of anything
        compl = list(store.objects(subject=thing, predicate=OWL.complementOf))
        if compl:
            return "( NOT %s )" % (manchesterSyntax(compl[0], store))
        else:
            prolog = "\n".join(["PREFIX %s: <%s>" % (k, nsBinds[k]) for k in nsBinds])
            qstr = (
                prolog
                + "\nSELECT ?p ?bool WHERE {?class a owl:Class; ?p ?bool ."
                + "?bool rdf:first ?foo }"
            )
            initb = {Variable("?class"): thing}
            for boolprop, col in store.query(qstr, processor="sparql", initBindings=initb):
                if not isinstance(thing, URIRef):
                    return manchesterSyntax(col, store, boolean=boolprop)
            try:
                prefix, uri, localname = store.compute_qname(thing)
                qname = ":".join([prefix, localname])
            except Exception:
                if isinstance(thing, BNode):
                    return thing.n3()
                # Expect the unexpected
                return thing.identifier if not isinstance(thing, str) else thing
            label = first(Class(thing, graph=store).label)
            if label:
                return label
            else:
                return qname

## `` propertyOrIdentifier

    propertyOrIdentifier(thing)

Source code in `rdflib/extras/infixowl.py`

    274
    275
    276
    277
    278
    279

    def propertyOrIdentifier(thing):  # noqa: N802
        if isinstance(thing, Property):
            return thing.identifier
        else:
            assert isinstance(thing, URIRef)
            return thing