Python inflection.camelize() Examples

The following are 27 code examples of inflection.camelize(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inflection , or try the search function .
Example #1
Source File: amazon.py    From cloudstorage with MIT License 6 votes vote down vote up
def _normalize_parameters(
        params: Dict[str, str], normalizers: Dict[str, str]
    ) -> Dict[str, str]:
        normalized = params.copy()

        for key, value in params.items():
            normalized.pop(key)
            if not value:
                continue

            key_inflected = camelize(underscore(key), uppercase_first_letter=True)
            # Only include parameters found in normalizers
            key_overrider = normalizers.get(key_inflected.lower())
            if key_overrider:
                normalized[key_overrider] = value

        return normalized 
Example #2
Source File: minio.py    From cloudstorage with MIT License 6 votes vote down vote up
def _normalize_parameters(
        params: Dict[str, str], normalizers: Dict[str, str]
    ) -> Dict[str, str]:
        normalized = params.copy()

        for key, value in params.items():
            normalized.pop(key)
            if not value:
                continue

            key_inflected = camelize(underscore(key), uppercase_first_letter=True)
            # Only include parameters found in normalizers
            key_overrider = normalizers.get(key_inflected.lower())
            if key_overrider:
                normalized[key_overrider] = value

        return normalized 
Example #3
Source File: utils.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def format_field_names(obj, format_type=None):
    """
    Takes a dict and returns it with formatted keys as set in `format_type`
    or `JSON_API_FORMAT_FIELD_NAMES`

    :format_type: Either 'dasherize', 'camelize', 'capitalize' or 'underscore'
    """
    if format_type is None:
        format_type = json_api_settings.FORMAT_FIELD_NAMES

    if isinstance(obj, dict):
        formatted = OrderedDict()
        for key, value in obj.items():
            key = format_value(key, format_type)
            formatted[key] = value
        return formatted

    return obj 
Example #4
Source File: __init__.py    From statsnba-playbyplay with MIT License 6 votes vote down vote up
def __init__(self, model_dict=None, **kwargs):
        """All attributes are CamelCased"""
        if isinstance(model_dict, dict):
            try:
                assert not kwargs
            except AssertionError:
                raise AssertionError(
                    'When using a dict to instantiate {0}, no other keywords should be supplied'.format(
                        self.__class__))
            else:
                kws = model_dict
        elif model_dict is None:
            kws = kwargs
        else:
            raise TypeError("Invalid arguments supplied")

        for key, value in kws.items():
            setattr(self, camelize(key.lower()),
                    value)  # Maybe just strip all non-required fields?
        self._validate_fields() 
Example #5
Source File: context.py    From dynamic-rest with MIT License 6 votes vote down vote up
def get_context(version, name, model, plural_name):
    name = inflection.underscore(inflection.singularize(name))
    model = model or name
    model_class_name = inflection.camelize(model)
    class_name = inflection.camelize(name)
    serializer_class_name = class_name + 'Serializer'
    viewset_class_name = class_name + 'ViewSet'
    plural_name = plural_name or inflection.pluralize(name)
    return {
        'version': version,
        'serializer_class_name': serializer_class_name,
        'viewset_class_name': viewset_class_name,
        'model_class_name': model_class_name,
        'name': name,
        'plural_name': plural_name
    } 
Example #6
Source File: db_sync.py    From target-postgres with GNU Affero General Public License v3.0 5 votes vote down vote up
def flatten_key(k, parent_key, sep):
    full_key = parent_key + [k]
    inflected_key = [inflect_column_name(n) for n in full_key]
    reducer_index = 0
    while len(sep.join(inflected_key)) >= 63 and reducer_index < len(inflected_key):
        reduced_key = re.sub(r'[a-z]', '', inflection.camelize(inflected_key[reducer_index]))
        inflected_key[reducer_index] = \
            (reduced_key if len(reduced_key) > 1 else inflected_key[reducer_index][0:3]).lower()
        reducer_index += 1

    return sep.join(inflected_key) 
Example #7
Source File: base.py    From benchling-api with MIT License 5 votes vote down vote up
def _camelize(cls, property=None):
        """Camelize the model name.

        :param property:
        :return:
        """
        name = inflection.underscore(cls.model_name)
        if property is not None:
            name += "_" + inflection.pluralize(property)
        else:
            name = inflection.pluralize(name)
        name = inflection.camelize(name)
        name = name[0].lower() + name[1:]
        return name 
Example #8
Source File: utils.py    From benchling-api with MIT License 5 votes vote down vote up
def un_underscore(k):
    """Transform keys like 'benchling_key' to 'benchlingKey'."""
    s = inflection.camelize(k)
    s = s[0].lower() + s[1:]
    return s 
Example #9
Source File: util.py    From diffy with Apache License 2.0 5 votes vote down vote up
def format_errors(messages: List[str]) -> dict:
    errors = {}
    for k, v in messages.items():
        key = camelize(k, uppercase_first_letter=False)

        if isinstance(v, dict):
            errors[key] = format_errors(v)

        elif isinstance(v, list):
            errors[key] = v[0]

    return errors 
Example #10
Source File: measures.py    From gs-quant with Apache License 2.0 5 votes vote down vote up
def esg_aggregate(asset: Asset, metric: EsgMetric, value_unit: Optional[EsgValueUnit] = None, *,
                  source: str = None, real_time: bool = False) -> Series:
    """
    Environmental, Social, and Governance (ESG) scores and percentiles for a broad set of companies across the globe.
    :param asset: asset object loaded from security master
    :param metric: name of ESG metric
    :param value_unit: the unit type of the metric value, one of percentile, score
    :param source: name of function caller
    :param real_time: whether to retrieve intraday data instead of EOD
    :return:
    """

    if real_time:
        raise NotImplementedError('real-time esg-aggregate not implemented')

    if metric != EsgMetric.ENVIRONMENTAL_SOCIAL_DISCLOSURE and value_unit is None:
        raise MqValueError("value_unit is required for metric {m}".format(m=metric.value))

    mqid = asset.get_marquee_id()
    if metric == EsgMetric.ENVIRONMENTAL_SOCIAL_DISCLOSURE:
        query_metric = inflection.camelize(metric.value, False)
    else:
        query_metric = "{metric}{unit}".format(metric=inflection.camelize(metric.value, False),
                                               unit=value_unit.value.capitalize())

    query_type = ESG_METRIC_TO_QUERY_TYPE.get(query_metric)
    _logger.debug('where assetId=%s, metric=%s, value_unit=%s, query_type=%s',
                  mqid, metric.value, value_unit.value if value_unit is not None else None, query_type.value)
    q = GsDataApi.build_market_data_query([mqid], query_type, source=source, real_time=real_time)
    _logger.debug('q %s', q)
    df = _market_data_timed(q)
    series = ExtendedSeries() if df.empty else ExtendedSeries(df[query_metric])
    series.dataset_ids = getattr(df, 'dataset_ids', ())
    return series 
Example #11
Source File: base.py    From gs-quant with Apache License 2.0 5 votes vote down vote up
def as_dict(self, as_camel_case: bool = False) -> dict:
        """Dictionary of the public, non-null properties and values"""
        if not self.__as_dict[as_camel_case]:
            raw_properties = self.properties()
            properties = (inflection.camelize(p, uppercase_first_letter=False) for p in raw_properties) \
                if as_camel_case else raw_properties
            values = (super(Base, self).__getattribute__(p) for p in raw_properties)
            self.__as_dict[as_camel_case] = dict((p, v) for p, v in zip(properties, values) if v is not None)

        return copy.copy(self.__as_dict[as_camel_case]) 
Example #12
Source File: __init__.py    From cloudaux with Apache License 2.0 5 votes vote down vote up
def modify(item, output='camelized'):
    """
    Calls _modify and either passes the inflection.camelize method or the inflection.underscore method.

    :param item: dictionary representing item to be modified
    :param output: string 'camelized' or 'underscored'
    :return:
    """
    if output == 'camelized':
        return _modify(item, camelize)
    elif output == 'underscored':
        return _modify(item, underscore) 
Example #13
Source File: __init__.py    From cloudaux with Apache License 2.0 5 votes vote down vote up
def _modify(item, func):
    """
    Modifies each item.keys() string based on the func passed in.
    Often used with inflection's camelize or underscore methods.

    :param item: dictionary representing item to be modified
    :param func: function to run on each key string
    :return: dictionary where each key has been modified by func.
    """
    result = dict()
    for key in item:
        result[func(key)] = item[key]
    return result 
Example #14
Source File: schema.py    From lemur with Apache License 2.0 5 votes vote down vote up
def format_errors(messages):
    errors = {}
    for k, v in messages.items():
        key = camelize(k, uppercase_first_letter=False)
        if isinstance(v, dict):
            errors[key] = format_errors(v)
        elif isinstance(v, list):
            errors[key] = v[0]
    return errors 
Example #15
Source File: schema.py    From lemur with Apache License 2.0 5 votes vote down vote up
def camel(self, data, many=None):
        items = []
        if many:
            for i in data:
                items.append(
                    {
                        camelize(key, uppercase_first_letter=False): value
                        for key, value in i.items()
                    }
                )
            return items
        return {
            camelize(key, uppercase_first_letter=False): value
            for key, value in data.items()
        } 
Example #16
Source File: models.py    From betfair.py with MIT License 5 votes vote down vote up
def __new__(meta, name, bases, attrs):
        for name, attr in six.iteritems(attrs):
            if isinstance(attr, types.BaseType):
                camelized = inflection.camelize(name, uppercase_first_letter=False)
                attr.serialized_name = attr.serialized_name or camelized
                attr.deserialize_from = attr.deserialize_from or camelized
        return super(BetfairModelMeta, meta).__new__(meta, name, bases, attrs) 
Example #17
Source File: utils.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def format_value(value, format_type=None):
    if format_type is None:
        format_type = json_api_settings.FORMAT_FIELD_NAMES
    if format_type == 'dasherize':
        # inflection can't dasherize camelCase
        value = inflection.underscore(value)
        value = inflection.dasherize(value)
    elif format_type == 'camelize':
        value = inflection.camelize(value, False)
    elif format_type == 'capitalize':
        value = inflection.camelize(value)
    elif format_type == 'underscore':
        value = inflection.underscore(value)
    return value 
Example #18
Source File: submodule_loader.py    From pclpy with MIT License 5 votes vote down vote up
def generate_loader(module, headers):
    lines = [common_includes]
    a = lines.append
    a(cpp_header)

    for header in headers:
        inc_name = '%s/%s' % (module, header) if module != "base" else header
        include_expression = '#include "%spp"' % (inc_name,)
        a(include_expression)
    a("\n")
    a("void define%sClasses(py::module &m) {" % camelize(module))

    # add submodule
    submodule_object_name = ("m_%s" % module) if module != "base" else "m"
    module_python = module if module != "2d" else "module_2d"
    if submodule_object_name != "m":
        module_creation = '{i}py::module {obj_name} = m.def_submodule("{module_python}", "Submodule {sub}");'
        a(module_creation.format(obj_name=submodule_object_name, module_python=module_python, sub=module, i=INDENT))

    # add function calls
    sub = camelize(module) if module != "base" else ""
    for header in headers:
        name = function_definition_name(header_name=header)
        function_call = "{i}define{sub}{name}Classes({sub_name});".format(i=INDENT,
                                                                          name=name,
                                                                          sub_name=submodule_object_name,
                                                                          sub=sub)
        a(function_call)
    a("}")

    return "\n".join(lines) 
Example #19
Source File: instantiations.py    From pclpy with MIT License 5 votes vote down vote up
def generate_templated_class_calls(self):
        s = []
        for c in self.sorted_classes:
            template_types = []
            if c.get("template"):
                template_info = re.findall(r"<(.+)>", str(c["template"].replace("\n", "")))
                if template_info:
                    template_types = filter_template_types(template_info[0])

            if template_types:
                sub_module_name = self.sub_module_name(c["name"])
                types_list = self.classes_point_types.get(c["name"], [])
                if types_list:
                    s.append(self.repr_sub_module(c["name"]))
                    for types in types_list:
                        type_names = "_".join(map(format_class_name, types))
                        define = 'define{sub}{name}<{types}>({sub_module_name}, "{types_names}")'
                        add_pcl = lambda t: ("pcl::" + t) if t not in KEEP_ASIS_TYPES else t
                        types_str = ", ".join([add_pcl(t) for t in types])
                        define = define.format(sub=camelize(self.module),
                                               name=c["name"],
                                               sub_module_name=sub_module_name,
                                               types=types_str,
                                               types_names=type_names)
                        s.append(define)
            else:
                define = 'define{sub}{name}({sub_name})'
                define = define.format(sub=camelize(self.module), name=c["name"], sub_name=BASE_SUB_MODULE_NAME)
                s.append(define)
        return s 
Example #20
Source File: instantiations.py    From pclpy with MIT License 5 votes vote down vote up
def generate_instantiation_function(self, global_indent="", has_functions=False):
        """
        void define...Classes(py::module &m) { ... }
        """
        s = []
        a = s.append
        i = INDENT
        a("{ind}void define{sub}{name}Classes(py::module &{base}) {ob}")
        for var in self.variables:
            a("{ind}{i}%s" % define_variable(var))
        for enum in self.enums:
            enum = Enum(enum)
            a("{ind}{i}%s;" % enum.to_str(prefix=enum.cppenum["namespace"], class_var_name=BASE_SUB_MODULE_NAME))
        for line in self.generate_templated_class_calls():
            a("{ind}{i}%s;" % line)
        if has_functions:
            a("{ind}{i}define{sub}{name}Functions({base});")
        a("{ind}{cb}")

        data = {
            "ind": global_indent,
            "i": i,
            "base": BASE_SUB_MODULE_NAME,
            "name": function_definition_name(self.header_name),
            "sub": camelize(self.module),
            "ob": "{",
            "cb": "}"
        }
        return "\n".join([line.format(**data) for line in s]) 
Example #21
Source File: utils.py    From pclpy with MIT License 5 votes vote down vote up
def generate_main_loader(modules):
    modules = list(sorted(modules))
    s = [common_includes]
    a = s.append
    for module in modules:
        a("void define%sClasses(py::module &);" % camelize(module))
    a("")
    a("void defineClasses(py::module &m) {")
    for module in modules:
        a("%sdefine%sClasses(m);" % (INDENT, camelize(module)))
    a("}")
    return "\n".join(s) 
Example #22
Source File: utils.py    From pclpy with MIT License 5 votes vote down vote up
def function_definition_name(header_name):
    return camelize(header_name.replace(".h", "")).replace(" ", "") 
Example #23
Source File: modgenerator.py    From Fragscapy with MIT License 5 votes vote down vote up
def get_mod(mod_name):
    """Imports a mod from its name using `importlib`.

    Args:
        mod_name: The name of the mod (snake_case of CamelCase are accepted).

    Returns:
        The python class which corresponds to the modification.

    Raises:
        ImportError: The class was not found or it is not a subclass of `Mod`.

    Examples:
        >>> get_mod("DropOne")
        <class 'fragscapy.modifications.drop_one.DropOne'>
        >>> get_mod("drop_one")
        <class 'fragscapy.modifications.drop_one.DropOne'>
    """
    pkg_name = "{}.{}".format(MOD_PACKAGE, inflection.underscore(mod_name))
    mod_name = inflection.camelize(mod_name)

    pkg = importlib.import_module(pkg_name)
    try:
        mod = getattr(pkg, mod_name)
    except AttributeError:  # There is no class named correctly
        raise ImportError(
            "No class named {} in module {}"
            .format(mod_name, pkg_name)
        )

    if not issubclass(mod, Mod):
        raise ImportError(
            "{}.{} is not a subclass of `fragscapy.modifications.mod.Mod`"
            .format(pkg_name, mod_name)
        )

    return mod 
Example #24
Source File: _workflow.py    From argo-python-dsl with Apache License 2.0 4 votes vote down vote up
def submit(
        self,
        client: client.V1alpha1Api,
        namespace: str,
        *,
        parameters: Optional[Dict[str, str]] = None,
    ) -> V1alpha1Workflow:
        """Submit an Argo Workflow to a given namespace.

        :returns: V1alpha1Workflow, submitted Workflow
        """
        parameters = parameters or {}

        new_parameters: List[V1alpha1Parameter] = []
        for name, value in parameters.items():
            param = V1alpha1Parameter(name=name, value=value)
            new_parameters.append(param)

        if getattr(self.spec, "arguments"):
            for p in getattr(self.spec.arguments, "parameters", []):
                if p.name in parameters:
                    continue  # overridden
                elif not getattr(p, "value"):
                    default = getattr(p, "default")
                    if default is not None:
                        p.value = default
                    else:
                        raise Exception(f"Missing required workflow parameter {p.name}")

                new_parameters.append(p)

            self.spec.arguments.parameters = new_parameters
        elif parameters:
            raise AttributeError("The Workflow doesn't take any parameters.")

        body: Dict[str, Any]
        if not getattr(self, "validated", True):
            _LOGGER.debug(
                "The Workflow has not been previously validated."
                "Sanitizing for serialization."
            )
            body = camelize(self.to_dict())
        else:
            body = client.api_client.sanitize_for_serialization(self)

        # submit the workflow
        created: models.V1alpha1Workflow = client.create_namespaced_workflow(
            namespace, body
        )

        # return the computed Workflow
        return created 
Example #25
Source File: __main__.py    From lore with MIT License 4 votes vote down vote up
def _generate_template(type, parsed, **kwargs):
    env.require(lore.dependencies.INFLECTION)
    import inflection
    name = parsed.name
    kwargs = kwargs or {}
    for attr in ['keras', 'xgboost', 'sklearn']:
        if hasattr(parsed, attr):
            kwargs[attr] = getattr(parsed, attr)
    kwargs['major_version'] = sys.version_info[0]
    kwargs['full_version'] = env.PYTHON_VERSION
    notebooks = ['features', 'architecture']
    name = inflection.underscore(name)
    if type == 'notebooks':
        for notebook in notebooks:
            _generate_template(notebook, parsed, **kwargs)
        return

    if type == 'test':
        destination = os.path.join(inflection.pluralize(type), 'unit', 'test_' + name + '.py')
    elif type in notebooks:
        destination = os.path.join('notebooks', name, type + '.ipynb')
    else:
        destination = os.path.join(env.APP, inflection.pluralize(type), name + '.py')

    if os.path.exists(destination):
        sys.exit(ansi.error() + ' %s already exists' % destination)

    dir = os.path.dirname(destination)
    if not os.path.exists(dir):
        os.makedirs(dir)
        if type not in notebooks:
            open(os.path.join(dir, '__init__.py'), 'w')

    kwargs['app_name'] = env.APP
    kwargs['module_name'] = name
    kwargs['class_name'] = inflection.camelize(name)
    code = _render_template(type + '.py.j2', **kwargs)

    with open(destination, 'w+') as file:
        file.write(code)

    print(ansi.success('CREATED ') + destination) 
Example #26
Source File: base.py    From gs-quant with Apache License 2.0 4 votes vote down vote up
def __from_dict(self, values: dict):
        for prop in self.properties():
            if getattr(type(self), prop).fset is None:
                continue

            prop_value = values.get(prop, values.get(inflection.camelize(prop, uppercase_first_letter=False)))

            if prop_value is not None:
                additional_types = []
                prop_type = self.prop_type(prop, additional=additional_types)

                if prop_type is None:
                    # This shouldn't happen
                    setattr(self, prop, prop_value)
                elif issubclass(prop_type, dt.datetime):
                    if isinstance(prop_value, int):
                        setattr(self, prop, dt.datetime.fromtimestamp(prop_value / 1000).isoformat())
                    else:
                        import re
                        matcher = re.search('\\.([0-9]*)Z$', prop_value)
                        if matcher:
                            sub_seconds = matcher.group(1)
                            if len(sub_seconds) > 6:
                                prop_value = re.sub(matcher.re, '.{}Z'.format(sub_seconds[:6]), prop_value)

                        try:
                            setattr(self, prop, dateutil.parser.isoparse(prop_value))
                        except ValueError:
                            if str in additional_types:
                                setattr(self, prop, prop_value)
                elif issubclass(prop_type, dt.date):
                    try:
                        setattr(self, prop, dateutil.parser.isoparse(prop_value).date())
                    except ValueError:
                        if str in additional_types:
                            setattr(self, prop, prop_value)
                elif issubclass(prop_type, EnumBase):
                    setattr(self, prop, get_enum_value(prop_type, prop_value))
                elif issubclass(prop_type, Base):
                    if isinstance(prop_value, Base):
                        setattr(self, prop, prop_value)
                    else:
                        setattr(self, prop, prop_type.from_dict(prop_value))
                elif issubclass(prop_type, (list, tuple)):
                    item_type = self.prop_item_type(prop)
                    if issubclass(item_type, Base):
                        item_values = tuple(v if isinstance(v, (Base, EnumBase)) else item_type.from_dict(v)
                                            for v in prop_value)
                    elif issubclass(item_type, EnumBase):
                        item_values = tuple(get_enum_value(item_type, v) for v in prop_value)
                    else:
                        item_values = tuple(prop_value)
                    setattr(self, prop, item_values)
                else:
                    setattr(self, prop, prop_value) 
Example #27
Source File: __init__.py    From python-jsonschema-objects with MIT License 4 votes vote down vote up
def build_classes(self, strict=False, named_only=False, standardize_names=True):
        """
        Build all of the classes named in the JSONSchema.

        Class names will be transformed using inflection by default, so names
        with spaces in the schema will be camelcased, while names without
        spaces will have internal capitalization dropped. Thus "Home Address"
        becomes "HomeAddress", while "HomeAddress" becomes "Homeaddress" To
        disable this behavior, pass standardize_names=False, but be aware
        that accessing names with spaces from the namespace can be
        problematic.

        Args:
            strict: (bool) use this to validate required fields while creating the class
            named_only: (bool) If true, only properties with an actual title attribute will
                be included in the resulting namespace (although all will be generated).
            standardize_names: (bool) If true (the default), class names will be tranformed
                by camel casing

        Returns:
            A namespace containing all the generated classes

        """
        kw = {"strict": strict}
        builder = classbuilder.ClassBuilder(self.resolver)
        for nm, defn in iteritems(self.schema.get("definitions", {})):
            uri = python_jsonschema_objects.util.resolve_ref_uri(
                self.resolver.resolution_scope, "#/definitions/" + nm
            )
            builder.construct(uri, defn, **kw)

        if standardize_names:
            name_transform = lambda t: inflection.camelize(
                inflection.parameterize(six.text_type(t), "_")
            )
        else:
            name_transform = lambda t: t

        nm = self.schema["title"] if "title" in self.schema else self.schema["$id"]
        nm = inflection.parameterize(six.text_type(nm), "_")

        builder.construct(nm, self.schema, **kw)
        self._resolved = builder.resolved

        classes = {}
        for uri, klass in six.iteritems(builder.resolved):
            title = getattr(klass, "__title__", None)
            if title is not None:
                classes[name_transform(title)] = klass
            elif not named_only:
                classes[name_transform(uri.split("/")[-1])] = klass

        return python_jsonschema_objects.util.Namespace.from_mapping(classes)