Search code examples
pythonpython-3.xcode-generation

How can i convert automatic created code into a class instead of a string?


I'm trying to have a script create a file automatically by passing two parameters

  1. newName
  2. List of strings with elements to be added to the end of newName

This is what my result should look like:

def get_state_order() -> list[SquadState]:
    """Returns the order of the states of the exercise"""
    return [SquadState.DOWN, SquadState.UP]

However, unfortunately it looks like this, i.e. it consists of strings in the array. Unfortunately, I failed for a bit too long trying to convert each element of the list into a class object with the name exercise_name(elem).

def get_state_order() -> list[SquadState]:
    """Returns the order of the states of the exercise"""
    return ['SquadState.DOWN', 'SquadState.UP']

Here is my code

file = f"""
....
....
...
def get_state_order() -> list[{exercise_name.capitalize()}State]:
    \"\"\"Returns the order of the states of the exercise\"\"\"
    return {list(newName + abc for abc in states)}
...
....
...
"""

I tried to change the type of each elem from the list comprehension.

newName = exercise_name+"State."

this is the error i get everytime when i am trying to fix it with some type changing functions:

    Traceback (most recent call last):
  File "/Users/work/PycharmProjects/KI/et_ki/models/exercises/automatisierung.py", line 91, in <module>
    create_exercise_file(exercise_name, states)
  File "/Users/work/PycharmProjects/KI/et_ki/models/exercises/automatisierung.py", line 67, in create_exercise_file
    return {list(exercise_name(newName + abc) for abc in states)}
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/work/PycharmProjects/KI/et_ki/models/exercises/automatisierung.py", line 67, in <genexpr>
    return {list(exercise_name(newName + abc) for abc in states)}
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'str' object is not callable

Solution

  • You have a list of strings and when it is printed it includes proper quotes around the strings, there are several ways to get around this but the main issue is that when a list is printed it uses the representation of strings:

    >>> print(str("hi")) # what we want it to do
    hi
    >>> print(repr("hi")) # what it is actually doing
    'hi'
    >>> print(["hi", "there"]) # repr gets called for each element in a list
    ['hi', 'there']
    

    One easy way that seems like it'd be the most useful for your use case is to have a custom class that overrides the __repr__ method to pass the string directly:

    class Symbol(str):
        def __repr__(self):
            return self # don't add quotes or escape special characters
    

    Then you can wrap your strings that represent code symbols in this class to be represented raw:

    >>> x = Symbol("SquadState.UP")
    >>> print([x,x])
    [SquadState.UP, SquadState.UP]