Files
os-traits/os_traits/utils.py
Jay Pipes 23d81d4451 organize os_traits for the future
Sean Mooney had a good idea that for future-proofing the os-traits library and
ensuring that we don't have to deal with one giant const.py file, that we break
the library into various modules corresponding to the higher-level namespaces.

This patch adds some symbol-registration foo into a utils module and allows the
os_traits module and "leaf modules" to be called in the following way:

 import os_traits
 from os_traits.hw.cpu import x86

 assert os_traits.HW_CPU_X86_SSE42 == x86.SSE42
 assert x86.SSE42 == 'HW_CPU_X86_SSE42'

Change-Id: I0e8f50822ab67cb3be85ed3b935dd6cdb4436dbf
2017-04-05 16:01:33 +00:00

57 lines
1.7 KiB
Python

# -*- coding: utf-8 -*-
# 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.
import functools
import sys
import os_traits
def symbolize(mod_name, name):
"""Given a reference to a Python module object and a short string name for
a trait, registers a symbol in the module that corresponds to the full
namespaced trait name.
For example, if called like so:
:code:
# In file /os_traits/hw/cpu/x86.py
import functools
from os_traits import utils
mod_register = functools.partial(utils.symbolize, __name__)
mod_register('AVX2')
mod_register('SSE')
Would end up creating the following symbols:
os_traits.hw.cpu.x86.AVX2 with the value of 'HW_CPU_X86_AVX2'
os_traits.hw.cpu.x86.SSE with the value of 'HW_CPU_X86_SSE'
os_traits.HW_CPU_X86_AVX2 with the value of 'HW_CPU_X86_AVX2'
os_traits.HW_CPU_X86_SSE with the value of 'HW_CPU_X86_SSE'
"""
leaf_mod = sys.modules[mod_name]
value_base = '_'.join([m.upper() for m in mod_name.split('.')[1:]])
value = value_base + '_' + name.upper()
setattr(os_traits, value, value) # os_traits.HW_CPU_X86_SSE
setattr(leaf_mod, name.upper(), value) # os_traits.hw.cpu.x86.SSE
def register_fn(mod_name):
return functools.partial(symbolize, mod_name)