In the style of Higginbottom. Formerly staticv0id@reddit

  • 1 Post
  • 10 Comments
Joined 1 year ago
cake
Cake day: June 22nd, 2023

help-circle



  • My favorite way to implement this is with decorators. I used this to make a dispatch table for reading objects from a MySQL database.

    (Yes I know I should be using UserDict below. You should too and don’t subclass dict like I did.)

    class FuncRegistry(dict):
        """Creates a registry of hashable objects to function mappings."""
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
    
        def register_for(self, key: Hashable) -> Callable:
            """Decorator to register functions in the registry.
    
            Parameters
    
            key: Hashable
                The key which should point to this function
    
            Returns: Callable
                Returns a decorator that registers the function to the key"""
            def decorator(fn: Callable) -> Callable:
                self[key] = fn
                return fn
            return decorator
    
    qreg = FuncRegistry()
    
    @qreg.register_for('foobr')
    def handle_foobr(arg1, arg2):
        # do something here then
        return
    
    qreg['foobr']('ooo its an arg', 'oh look another arg')
    

    edit: formatting





  • I’m not complaining, just reflecting that it is weird to me. The static type checker is almost an admission that type checking is a Good Thing, but Python continues to resist adding runtime checking. Modules like typing and Protocol don’t seem to do anything at runtime, and because of that are deeply weird to me - what kind of include doesn’t have runtime code? I haven’t seen anything quite like it in any other language I’ve coded in. It just seems included for the coders’ IDE to throw warnings, and that’s it.

    Then again, it’s entirely possible I just don’t get around much. I’m not a software guy, I’m hardware, and occasionally I’ll write a tool or website to help with a specific task.

    I suppose the alternative is just as weird or weirder, where there are almost two separate languages, one strongly typed and one not typed at all.


  • Zeusbottom@sh.itjust.workstoPython@programming.devProtocols in Python
    link
    fedilink
    English
    arrow-up
    5
    arrow-down
    2
    ·
    1 year ago

    It’s very weird to me that Python, as an inherently untyped language, is trying to bolt on stronger typing through modules like Protocol and typing.

    If typing is a good thing, why not make it an optional first-class part of the language? Maybe make strong typing a one liner option at the top of a source file? This growing maze of modules and recommendations is so unwieldy. For example, the typing module works kind of in conjunction with language elements that aren’t what newbs learn in Python 101, like type specifiers in function args. I feel like this stuff is driving Python away from simplicity.