Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python nbtlib can't append a Compound into a List

I try to add a Compound into a List to make a Compound List

import nbtlib
from nbtlib.tag import *

CpdList = List(Compound())
Cpd = Compound()

Cpd['name'] = String("Name")
Cpd['test'] = Byte(0)

CpdList.append(Cpd)

>>> nbtlib.tag.IncompatibleItemType: Compound({'name': String('Name'), 'test': Byte(0)}) should be a End tag

I don’t understand what’s a End Tag and how to solve this issue

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to add a End tag to the Compound
Cpd['End'] = End

>Solution :

  • You just need to properly use nbtlib.tag.List with the Compound type and properly make a call:
import nbtlib
from nbtlib.tag import Compound, List, String, Byte

CpdList = List[Compound]()
Cpd = Compound()
Cpd['name'] = String("Name")
Cpd['test'] = Byte(0)

CpdList.append(Cpd)

print(CpdList)

Note:

Note that the nbtlib.tag.List expects the same type of elements, and the Compound type is not directly allowed in a List tag. The error mentions the need for an End tag, which is a terminator for Compound tags.


In case you need a dynamic type list, you can use python native list():

import nbtlib
from nbtlib.tag import Compound, String, Byte

CpdList = list[Compound]()
Cpd = Compound()
Cpd['name'] = String("Name")
Cpd['test'] = Byte(0)

CpdList += [Cpd, 0, 'alice', {1: 2}]

print(CpdList)

Prints

[Compound({'name': String('Name'), 'test': Byte(0)}), 0, 'alice', {1: 2}]

Which is same as:


import nbtlib
from nbtlib.tag import Compound, String, Byte

CpdList = list(Compound())
Cpd = Compound()
Cpd['name'] = String("Name")
Cpd['test'] = Byte(0)

CpdList += [Cpd, 0, 'alice', {1: 2}]

print(CpdList)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading