'How does my list become ObservedList? Problem with replit db
I have a problem with making discord bot on repl.it, my list is 'ObservedList' and i dont know what to do with this, when I watch some tutorials its always just a normal list
from replit import db
db['fruits'] = ['apple','banana']
print(db['fruits'])
Output:
ObservedList(value=['apple', 'banana'])
Solution 1:[1]
When poking around in the link provided in the previous answer, I found some interesting things in the __init__ function.
def __init__(
self, on_mutate: Callable[[List], None], value: Optional[List] = None
) -> None:
self._on_mutate_handler = on_mutate
if value is None:
self.value = []
else:
self.value = value
If you want to get the list in an ObserverdList called foo, use foo.value to do so.
For example:
Output = [“Apple”, “Banana”] + db[“foo”].value
Assuming the ObservedList in db[“foo”] is just [“Cantaloupe”], the return would be[“Apple”]
Solution 2:[2]
ObservedList
is a class in the replit package
As stated in the docstring it is
A list that calls a function every time it is mutated.
There is also ObservedDict
class.
There is this tutorial that shed some more light in Advanced Usage section at the bottom:
Another problem you might encounter is related to the mutation feature. Under the hood, this feature works by replacing the primitive list and dict classes with special replacements that listen for mutation, namely replit.database.database.ObservedList and replit.database.ObservedDict.
To JSON encode these values, use the replit.database.dump method. For JSON responses in the web framework, this is done automatically.
To convert these classes to their primitive equivalent, access the value attribute. A function that automatically does this is provided: replit.database.to_primitive.
To avoid this behavior entirely, use the get_raw and set_raw methods instead.
Solution 3:[3]
At the moment you are asking the bot to print the entire list. If you change your code to:
print(db['fruits'][0])
Output would then be
apple
This is quite an old questions but I hope this answered the question simply.
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 | |
Solution 2 | |
Solution 3 | DarcyParsley |