Python3 checking entity components

32 views
Skip to first unread message

larr...@gmail.com

unread,
Nov 26, 2017, 12:32:42 PM11/26/17
to KivEnt
So far I've been doing something like this to check if an entity has a particular component:

if hasattr(entity,'movement'):
    #For entities without physics
    entity.movement.vx += component.ax
    entity.movement.vy += component.ay
#Apply acceleration to cymunk_physics if present
elif hasattr(entity,'cymunk_physics'):
    body = entity.cymunk_physics.body
    body.velocity += (component.ax,component.ay)

However I found that in python 3 this actually does not work because hasattr is implemented by calling getattr, leading to the following:


File "/Users/sfasd/Code/ElectricNemo/electricnemo/electricnemo.py", line 441, in update
     if hasattr(entity,'movement'):
   File "kivent_core/entity.pyx", line 57, in kivent_core.entity.Entity.__getattr__ (kivent_core/entity.c:2472)
 kivent_core.entity.NoComponentActiveError: Entity 1 has no component active for movement


Is there a more proper way of checking for presence or absence of a component?

Avour

unread,
Oct 23, 2019, 3:12:14 PM10/23/19
to KivEnt

By creating your custom hasattr func
def hasattr(obj, atr):
   try:
      getattr(obj, attr)
      return True
   except kivent_core.entities.NoComponentActiveError:
       return False
Reply all
Reply to author
Forward
0 new messages