'How to empty a yattag doc
I'm having rather good results in using yattag
to generate HTML code within my python project.
But there is something I don't understand and I actually couldn't find it in the package documentation. I would like to reset the content of the Doc in order to start from an empty page.
Have a look at the code snippet below:
from yattag import Doc
doc, tag, text, line = Doc().ttl()
def main():
print('First page')
line('p', 'This is a line in the first page')
doc.nl()
print(doc.getvalue())
# here I would like to reset the doc content!!!
print('Second page')
line('p', 'This is a line in the second page')
doc.nl()
print(doc.getvalue())
if __name__ == "__main__":
main()
The output is as follows:
First page
This is a line in the first page
Second page
This is a line in the first page
This is a line in the second page
One solution I have found was to move the doc, tag, text, line = Doc().ttl()
inside the main definition and to re-call it in between the two pages, but I'm not sure about memory leakage. Do I need to perform some garbage collection manually?
Many thanks for your help!
Solution 1:[1]
You can get a quick answer for this question yourself by making a temporary change to your code so that it does the stuff you worry about requiring garbage collection in a leak, as in:
from yattag import Doc
doc, tag, text, line = Doc().ttl()
def main():
while True:
foo()
def foo():
doc, tag, text, line = Doc().ttl()
print('First page')
line('p', 'This is a line in the first page')
doc.nl()
print(doc.getvalue())
# here I would like to reset the doc content!!!
doc, tag, text, line = Doc().ttl()
print('Second page')
line('p', 'This is a line in the second page')
doc.nl()
print(doc.getvalue())
if __name__ == "__main__":
main()
If having the call to Doc().ttl() in multiple places is problematic, which I wouldn't expect, this modified program should eventually crash.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tim Boddy |