Skip to content

Instantly share code, notes, and snippets.

@WolfpackWilson
Last active August 22, 2020 22:01
Show Gist options
  • Save WolfpackWilson/6c2fdfe0c1b20222313bbaa9156f0c89 to your computer and use it in GitHub Desktop.
Save WolfpackWilson/6c2fdfe0c1b20222313bbaa9156f0c89 to your computer and use it in GitHub Desktop.
Sample code from one of my projects for Python learning purposes. The purpose of this class is to format and create XML tag sets based on the information it is given.
import re
class Tag:
NAME_RE = re.compile(r'(^xml)|(^[0-9]*)', re.IGNORECASE)
def __init__(self, tag_name: str, **attrs):
"""Create and store XML tag information in the proper formatting.
Parameters
----------
tag_name: str
The name that will be displayed.
attrs
The attributes to add.
"""
self._name = self.format_name(tag_name)
self._attrs = {
self.format_name(key): value
for key, value in attrs.items()
}
@property
def name(self) -> str:
"""Return the name of the tag."""
return self._name
@property
def attrs(self) -> dict:
"""Return a dictionary of the tag attributes in the form {attr: value}."""
return self._attrs
@property
def open_tag(self) -> str:
"""Return the formatted opening tag."""
tag = "<" + self._name
if len(self._attrs) > 0:
# add the attributes
tag += " " + " ".join(
f'{key}="{value}"'
for key, value in self._attrs.items()
)
return tag + ">"
@property
def close_tag(self) -> str:
"""Return the formatted closing tag."""
return f"</{self._name}>"
@staticmethod
def format_name(text: str) -> str:
"""Return a string formatted to XML tag naming conventions."""
text = Tag.NAME_RE.sub('', text)
return text.strip('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
def enclose(self, text: str, tabs: int = 0):
"""Return a string enclosed with the tag."""
return "\t" * tabs + self.open_tag + text + self.close_tag + "\n"
def add_attr(self, attr: str, value):
"""Add an attribute to the tag."""
attr = self.format_name(attr)
self._attrs[attr] = value
def rm_attr(self, attr):
"""Remove and return a tag attribute."""
attr = self.format_name(attr)
return self._attrs.pop(attr)
if __name__ = '__main__':
example_tag = Tag('example', lang='English')
print(example_tag.enclose('This is an example'))
@WolfpackWilson
Copy link
Author

If this were to run on its own, it would output the following:

<example lang="English">
    This is an example.
</example>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment