Assigned variable cannot be found

Question

I was making an XML class, but then this weird error came that I don’t even understand.
Can someone help?

Code

class XML:
  def __init__(self, name: str, attrs: dict[str, str | bool], innerText = None, contains_inner_text: bool = True) -> None:
    self.name: str = str(name)
    self.attrs: dict[str, str | bool] = attrs
    self.contains_inner_text = contains_inner_text
    self.innerText = str(innerText)
    if isinstance(innerText, XML):
      self.innerXML = innerText

  def attrs_str(self) -> str:
    result = ''
    for attr in self.attrs:
      value = self.attrs[attr]
      if value == True: result += attr
      else: result += f'{attr}="{value}"'
    return result
    
  def __str__(self) -> str:
    if not self.contains_inner_text: return f'<{self.name}>'
    return  f'<{self.name}{" " if self.attrs_str() != "" else ""}{self.attrs_str()}>{self.innerText}</{self.name}>'

  def format(self, indent: int = 2) -> str:
    if not self.contains_inner_text: return f'<{self.name}>'
    in_xml = False
    try:
      self.innerXML
      in_xml = True
    except AttributeError: innerTextResult = {self.innerText}
    if in_xml: innertTextResult = {self.innerXML.format()}
    return f'<{self.name}{" " if self.attrs_str() != "" else ""}{self.attrs_str()}>\n{" " * indent}{innerTextResult}\n</{self.name}>'

doc = XML('Document', {'name': 'untitled'}, XML('text', {}, 'Hello World!'))

print(doc.format())

Error

Traceback (most recent call last):
  File "main.py", line 35, in <module>
    print(doc.format())
  File "main.py", line 31, in format
    return f'<{self.name}{" " if self.attrs_str() != "" else ""}{self.attrs_str()}>{innerTextResult}</{self.name}>'
UnboundLocalError: local variable 'innerTextResult' referenced before assignment

I suspect that when innerTextResult is assigned to in the except statement, it is only defined within the try except statement, and not in the general scope of the format function. Try defining innerTextResult above the try except statement and just assigning it None.

2 Likes

But that breaks the result.

2 Likes

How?

What I’m suggesting is this:

def format(self, indent: int = 2) -> str:
  if not self.contains_inner_text: return f'<{self.name}>'
  in_xml = False
  innerTextResult = None
  try:
    self.innerXML
    in_xml = True
  except AttributeError: innerTextResult = {self.innerText}
  if in_xml: innertTextResult = {self.innerXML.format()}
  return f'<{self.name}{" " if self.attrs_str() != "" else ""}{self.attrs_str()}>\n{" " * indent}{innerTextResult}\n</{self.name}>'

Does that cause an error?

Oh actually, just realised:

You misspelt the variable name, that might be what’s causing the error lol innertTextResult should be innerTextResult .

5 Likes

Yep. The typo was the problem. Thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.