Skip to content
This repository has been archived by the owner on Sep 20, 2024. It is now read-only.

General: Event callbacks pass event to callbacks as expected #4210

Merged
merged 1 commit into from
Dec 16, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 40 additions & 6 deletions openpype/lib/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,22 +74,52 @@ def __init__(self, topic, func):
"Registered callback is not callable. \"{}\""
).format(str(func)))

# Collect additional data about function
# - name
# - path
# - if expect argument or not
# Collect function name and path to file for logging
func_name = func.__name__
func_path = os.path.abspath(inspect.getfile(func))

# Get expected arguments from function spec
# - positional arguments are always preferred
expect_args = False
expect_kwargs = False
fake_event = "fake"
if hasattr(inspect, "signature"):
# Python 3 using 'Signature' object where we try to bind arg
# or kwarg. Using signature is recommended approach based on
# documentation.
sig = inspect.signature(func)
expect_args = len(sig.parameters) > 0
try:
sig.bind(fake_event)
expect_args = True
except TypeError:
pass

try:
sig.bind(event=fake_event)
expect_kwargs = True
except TypeError:
pass

else:
expect_args = len(inspect.getargspec(func)[0]) > 0
# In Python 2 'signature' is not available so 'getcallargs' is used
# - 'getcallargs' is marked as deprecated since Python 3.0
try:
inspect.getcallargs(func, fake_event)
expect_args = True
except TypeError:
pass

try:
inspect.getcallargs(func, event=fake_event)
expect_kwargs = True
except TypeError:
pass

self._func_ref = func_ref
self._func_name = func_name
self._func_path = func_path
self._expect_args = expect_args
self._expect_kwargs = expect_kwargs
self._ref_valid = func_ref is not None
self._enabled = True

Expand Down Expand Up @@ -157,6 +187,10 @@ def process_event(self, event):
try:
if self._expect_args:
callback(event)

elif self._expect_kwargs:
callback(event=event)

else:
callback()

Expand Down