blob: 3f1e028b001b8dbd115b50691b7fb6de7b90732a [file] [log] [blame]
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +00001# $Copyright:
2# ----------------------------------------------------------------
3# This confidential and proprietary software may be used only as
4# authorised by a licensing agreement from ARM Limited
5# (C) COPYRIGHT 2015 ARM Limited
6# ALL RIGHTS RESERVED
7# The entire notice above must be reproduced on all authorised
8# copies and copies may only be made to the extent permitted
9# by a licensing agreement from ARM Limited.
10# ----------------------------------------------------------------
11# File: dynamic.py
12# ----------------------------------------------------------------
13# $
14#
15
16"""The idea is to create a wrapper class that
17returns a Type of a Class dynamically created based
18on the input parameters. Similar to a factory design
19pattern
20"""
21from cr2.base import Base
22import re
23from cr2.run import Run
24
25
Javi Merino6f34d902015-02-21 11:39:09 +000026def default_init(self):
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000027 """Default Constructor for the
28 Dynamic MetaClass
29 """
30
31 super(type(self), self).__init__(
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000032 unique_word=self.unique_word,
33 )
34
35
36class DynamicTypeFactory(type):
37
38 """Override the type class to create
39 a dynamic type on the fly
40 """
41
42 def __new__(mcs, name, bases, dct):
43 """Override the new method"""
44 return type.__new__(mcs, name, bases, dct)
45
46 def __init__(cls, name, bases, dct):
47 """Override the constructor"""
48 super(DynamicTypeFactory, cls).__init__(name, bases, dct)
49
50
51def _get_name(name):
52 """Internal Method to Change camelcase to
53 underscores. CamelCase -> camel_case
54 """
55 return re.sub('(?!^)([A-Z]+)', r'_\1', name).lower()
56
57
58def register_dynamic(class_name, unique_word, scope="all"):
59 """Create a Dynamic Type and register
60 it with the cr2 Framework"""
61
62 dyn_class = DynamicTypeFactory(
63 class_name, (Base,), {
64 "__init__": default_init,
65 "unique_word": unique_word,
66 "name": _get_name(class_name)
67 }
68 )
69 Run.register_class(dyn_class, scope)
70 return dyn_class
71
72
73def register_class(cls):
74 """Register a new class implementation
75 Should be used when the class has
76 complex helper methods and does not
77 expect to use the default constructor
78 """
79
80 # Check the argspec of the class
81 Run.register_class(cls)