Caching search results
Holding the function in a variable will not help you here as it will still run twice as you have two calls to it.
i mean it like this:
...
sprites = sprite_list()
if own['counter'] < len(sprites): # first usage
# second usage
logic.getSceneList()[0].addObject(sprites[own['counter']],logic.getSceneList()[0].objects['AssetsLevelSpawn'],200)
own['counter'] += 1
else:
own['sprites'] = True
...
Repeating the search makes sense when you can’t be sure the list changed between the usages and you want to get the updated list. This is not the case in your situation. It would be the case if you add or remove objects between the two usages.
Condition checking
When you are sure your property contains boolean values only, you do not need to explicit check for them. The “if” statement always expect a boolean condition.
a = True
if a:
print("a was validated to True - one operation")
if a == True:
print("a was compered against True, which is validated against True - two operations")
But there are more things to consider. In Python a validation expression as well as a compare operation include implicit type conversion. Therefore:
- True -> True
- False -> False
- None -> False
- 1 -> True
- 1.0 -> True
- other number -> False
- String -> False
- empty collection (list, dict) -> False
- non-empty collection -> True
Get()
In your situation you should only get (and expect) a boolean value. Otherwise you get incorrect data in that property.
using get() is pretty straight-forward:
if not own.get('sprites'):
I suggest to use this when the property is optional. Use the [] syntax when the property is mandatory (must exist before the call).
Get is a mighty tool. The real call is:
get(key, defaultvalue=None)
This means you can do things like that:
if not own.get('sprites', False):
...
count = own.get('counter', 0)
Be aware it returns a default value, it will not create a property. The property will still not be present, but you have a value you can process with.
Before you go and replace all [] with get() - creating a default value needs processing power. The default value will only be needed when the property is not present. You need to take into account the processing time of creating the default vs. the time you really need it. This means complex default values (like lists, custom classes) should be avoided for efficiency. In this case the [] syntax is better even when it requires additional verification checks.