Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Registering a hook function in a derived class wipes out any hooks already registered in the base class. #3124

Closed
naylor-b opened this issue Feb 21, 2024 · 0 comments · Fixed by #3125
Assignees
Labels

Comments

@naylor-b
Copy link
Member

Description

See title.

Example

import openmdao.api as om
import openmdao.utils.hooks as hooks

def build_model(name='problem1', prob=None):
if prob is None:
prob = om.Problem(name=name)
prob.calls = []
model = prob.model

model.add_subsystem('p1', om.IndepVarComp('x', 3.0))
model.add_subsystem('p2', om.IndepVarComp('y', -4.0))
model.add_subsystem('comp', om.ExecComp("f_xy=2.0*x+3.0*y"))

model.connect('p1.x', 'comp.x')
model.connect('p2.y', 'comp.y')
prob.setup()
return prob

def main():
def inherited_hook_pre(prob, **kwargs):
prob.calls.append('inherited_pre')

def inherited_hook_post(prob, **kwargs):
    prob.calls.append('inherited_post')

def base_hook_pre(prob, **kwargs):
    prob.calls.append('base_pre')

def base_hook_post(prob, **kwargs):
    prob.calls.append('base_post')

hooks._register_hook('final_setup', 'MyProblem', pre=inherited_hook_pre, post=inherited_hook_post)
hooks._register_hook('final_setup', 'Problem', pre=base_hook_pre, post=base_hook_post)

prob = MyProblem()
build_model(prob=prob)

prob.run_model()
prob.run_model()
prob.run_model()

assert prob.calls == ['inherited_pre', 'base_pre', 'inherited_post', 'base_post', 'inherited_pre',
                                'base_pre', 'inherited_post', 'base_post', 'inherited_pre', 'base_pre', 'inherited_post', 'base_post']

hooks._unregister_hook('final_setup', 'Problem', pre=base_hook_pre, post=False)

prob.calls = []

prob.run_model()
prob.run_model()

assert prob.calls == ['inherited_pre', 'inherited_post', 'base_post', 'inherited_pre', 'inherited_post', 'base_post']

class MyProblem(om.Problem):
def init(self, *args, **kwargs):
super().init(*args, **kwargs)
self.calls = []

def run_model(self):
    super().run_model()

main()

OpenMDAO Version

3.30.1

Relevant environment information

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants