Skip to content

Instantly share code, notes, and snippets.

@dhilst
Created September 28, 2017 17:30
Show Gist options
  • Save dhilst/428f2fa4a0663150f20e1e0c4e445ef6 to your computer and use it in GitHub Desktop.
Save dhilst/428f2fa4a0663150f20e1e0c4e445ef6 to your computer and use it in GitHub Desktop.
Monkey patching injector decorators.
# Copyright 2017 Daniel Hilst Selli, <danielhilst@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from importlib import import_module
def inject_func(target):
def decorator(func):
module_spec, target_func = target.rsplit('.', 1)
module = import_module(module_spec)
func.target = getattr(module, target_func)
setattr(module, target_func, func)
return func
return decorator
def inject_class(target):
def decorator(proxy_cls):
module_spec, target_spec = target.rsplit('.', 1)
module = import_module(module_spec)
target_cls = getattr(module, target_spec)
proxyobj = type(target_cls.__name__, (proxy_cls, target_cls), {'_target': target_cls})
setattr(module, target_spec, proxyobj)
return proxyobj
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment