Skip to main content

module for XML representations

Project description

Overview

xmlrepr module is used to have a nice representations for objects in xml formats.

simple

The module only contains one function called repr, which has different behavior depending on the first positional argument arg1 as follows:

  1. xmlrepr.repr(x) is the same as repr(x) when x is not str and doesn't implement __xml__ method.

  2. xmlrepr.repr(x) will make a call to x.__xml__(level) method if available. otherwise it behaves the same as built-in repr function.

  3. If arg1 (the first argument) is str: the function will return xml string which the root tag name is arg1. In that case, the function will also accept *children and **props parameters to customize the generated xml string.

Note: the source code will be available at the end of this page.

Examples

Let's see some examples to understand the module easily.

from xmlrepr import repr

# Example 1

print(repr({
    'key1':'value1',
    'key2':'value2',
}))

# Output
# "{'key1': 'value1', 'key2': 'value2'}"

# dict object don't have '__xml__' method

# Example 2

import typing

class Foo1(typing.NamedTuple):
    name: str
    value: int
    
    def __xml__(self, level=0):
        return f'<{self.name} value="{self.value}" />'
    
    __str__ = __xml__

foo = Foo1('foo', 49)
print(foo)

# Output
# '<foo value="49" />'

# Example 3

class Foo2(object):
    def __init__(self, name, children, **properties):
        self.name = name
        self.children = children
        self.props = properties
    
    def __xml__(self, level=0):
        return repr(
            self.name, # str
            *self.children,
            # don't forget this
            level= level,
            **self.properties,
        )
    
    __repr__ = __str__ = __xml__

parent_foo = Foo2('master', [foo], sympole="$", ignore=True)
print(parent_foo)

''' Output
<master sympole="$" ignore>
<foo value="49" />
</master>
'''

# To fix indentation we should fix __xml__ method of Foo1

def __fix_xml__(self, level=0):
    return repr(
        self.name,
        level= level,
        value= self.value,
    )

setattr(Foo1, '__xml__', __fix_xml__) # fixed

# let's also switch 'ignore' property for testing
parent_foo.props['ignore'] = False

print(parent_foo)

'''Output
<master sympole="$">
    <foo value="49" />
</master>
'''

Source Code

Here is how repr function is implemented.

def repr(arg1, *children, level=0, **props):
    if type(arg1) != str:
        if '__xml__' in dir(arg1):
            # calling '__xml__' method if implemented
            return arg1.__xml__(level)
        else:
            # calling built-in function 'repr'
            return globals()['__builtins__'].repr(arg1)
    
    # 'name', 'indent' and 'props' variables
    name = arg1
    indent = '    ' * level # 4 spaces per level
    props = ' '.join(
        '%s="%s"' % item if item[1] != True else item[0]
        for item in props.items() if item[1] != False
    )
    
    # returning xml tag string
    if children:
        # regular xml tag
        return '\n'.join([
            f"{indent}<{name} {props}>",
            f"{indent}" + f"\n{indent}".join(
                repr(child, level= level + 1)
                for child in children
            ),
            f"{indent}</{name}>",
        ])
    else:
        # self-closing xml tag
        return f"{indent}<{name} {props} />"

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

xmlrepr-0.0.1.tar.gz (4.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

xmlrepr-0.0.1-py3-none-any.whl (4.4 kB view details)

Uploaded Python 3

File details

Details for the file xmlrepr-0.0.1.tar.gz.

File metadata

  • Download URL: xmlrepr-0.0.1.tar.gz
  • Upload date:
  • Size: 4.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.5.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.0 CPython/3.8.3

File hashes

Hashes for xmlrepr-0.0.1.tar.gz
Algorithm Hash digest
SHA256 d73cc5e7df84e0d84a667751fb5538dc16e16b1324a65664ae0f707971d74442
MD5 623dad7b93806e093411860ae8d89732
BLAKE2b-256 c80836d582ad252606793be9135d371d5abfc7585f25928bc4651b04379c47b0

See more details on using hashes here.

File details

Details for the file xmlrepr-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: xmlrepr-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 4.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.5.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.0 CPython/3.8.3

File hashes

Hashes for xmlrepr-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4016e708970bcdbff2b8a8bea8c5ac16ec9dc87de18389c1b37dc9a296422bd6
MD5 31eec975f57bf2c55b5275267d78813f
BLAKE2b-256 19974928ebfdb620c6a0f3ae2f1d748f37c0e2d6f423669224605e04c8e5ecb0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page