Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to on Import PEP8 the Package

If I am importing a module from a 3rd party, but the syntax they use does not line up with mine, is there a good way to pep8 it?

Example: I need to use a 3rd party module that I cannot edit and their naming convention isn't so great.

Example:

thisIsABase_function(self,a,b)

I have some code that pepifies the name to pep8, but I was wondering how I can make the functions accessible by that new pep8 name?

def _pep8ify(name):
    """PEP8ify name"""
    import re
    if '.' in name:
        name = name[name.rfind('.') + 1:]
    if name[0].isdigit():
        name = "level_" + name
    name = name.replace(".", "_")
    if '_' in name:
        return name.lower()
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

Is there a way I can PEP8 these names on import?

like image 267
code base 5000 Avatar asked Jan 29 '18 14:01

code base 5000


1 Answers

You can use a context manager to automatically pep8ify the symbols from an imported module like:

Example:

with Pep8Importer():
    import funky

Code:

class Pep8Importer(object):

    @staticmethod
    def _pep8ify(name):
        """PEP8ify name"""
        import re
        s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
        return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

    def __enter__(self):
        # get list of current modules in namespace
        self.orig_names = set(dir(sys.modules[__name__]))

    def __exit__(self, exc_type, exc_val, exc_tb):
        """ Pep8ify names in any new modules

        Diff list of current module names in namespace.
        pep8ify names at the first level in those modules
        Ignore any other new names under the assumption that they
        were imported/created with the name as desired.
        """
        if exc_type is not None:
            return
        new_names = set(dir(sys.modules[__name__])) - self.orig_names
        for module_name in (n for n in new_names if not n.startswith('_')):
            module = sys.modules[module_name]
            for name in dir(module):
                pep8ified = self._pep8ify(name)
                if pep8ified != name and not name.startswith('_'):
                    setattr(module, pep8ified, getattr(module, name))
                    print("In mModule: {}, added '{}' from '{}'".format(
                        module_name, pep8ified, name))

Test Code:

with Pep8Importer():
    import funky

print(funky.thisIsABase_function)
print(funky.this_is_a_base_function)

funky.py

thisIsABase_function = 1

Results:

In module: funky, added 'this_is_a_base_function' from 'thisIsABase_function'

1
1
like image 178
Stephen Rauch Avatar answered Oct 10 '22 02:10

Stephen Rauch