Hi Bruno,

On 3/27/24 9:34 AM, Bruno Haible wrote:
> It will also help further development: In large pieces of code, it's
> easier to understand the existing code and make modifications if there
> are type annotations with a decent syntax.
> (By "decent syntax" I do *not* mean the K&R C syntax or the Common Lisp
> syntax with DECLARE, nor the GNU C attributes syntax:

Yes, we are in agreement there. Especially the part about K&R C. :)
I am a big fan of the GNU C attributes for warnings, nonnull and
warn_unused_result, for example. I assume most of the syntax
strangeness is from remaining compliant with ISO C, correct? Using the
'__*' reserved namespace and such.

> Still, three remarks:
> 
>   * In GLConfig.py, it is pointless to enumerate all the possible value
>     types:
>       str | float | int | bool | classes.CopyAction | list[str] | None
>     You could just as well use Any (or any), I guess?

Yes, I think that would be more correct. It looks like 'Any' is from
the 'typing' module [1]. It would silence type checkers from warning
you "you can't do this str operation on a union type". This patch I
was trying not to introduce *too* much and Any was one more thing I
wasn't familiar with.

For what it's worth, I would like to change that class around anyways.
In most places it is used like an extended dictionary. One exception
to this is GLImport.actioncmd():

       def actioncmd(self) -> str:
        '''Return command-line invocation comment.'''
        modules = self.config.getModules()
        avoids = self.config.getAvoids()
        destdir = self.config.getDestDir()

Here is GLImport.gnulib_cache() for comparison:

    def gnulib_cache(self) -> str:
        '''omitted...'''
        emit = ''
        moduletable = self.moduletable
        actioncmd = self.actioncmd()
        localpath = self.config['localpath']
        sourcebase = self.config['sourcebase']

The first one makes much more sense to me. For type hinting it is much
clearer. It would remove most of the union stuff. Equally important,
it is much easier to see an undefined function call than a bad key.
The latter you would not find unless you run tests and hit a code path
which raises a key error.

Since this is done in GLImport.actioncmd, maybe this was the goal
anyways? Someone just didn't get around to finishing it?

>   * In GLModuleSystem.py lines 784, 821:
>     A condition can be a string or True. But
>       str | bool
>     makes it look like False was also a valid value. Is possible to
>     write
>       str | True
>     in some way?

Yes, I did not know about this until yesterday night but apparently
there is 'Literal' from the 'typing' module for this [2]. I didn't add
it because I wasn't sure of any comparability issues. I figured it was
best to save for another patch.

We would have to double check comparability with Python 3.7+, though I
think it should be safe. But it looks like we can do something like
this for GLConfig.getLGPL() which is another example of this:

    def setLGPL(self, lgpl: str | bool | None) -> None:
        '''Abort if modules aren't available under the LGPL.
        Default value is None, which means that lgpl is disabled.'''
        if lgpl in [None, True, '2', '3orGPLv2', '3']:
           # do something or raise type error

becomes:

    def setLGPL(self, lgpl: Literal[None, True, '2', '3orGPLv2', '3']) -> None:
        '''Abort if modules aren't available under the LGPL.
        Default value is None, which means that lgpl is disabled.'''
        if lgpl in [None, True, '2', '3orGPLv2', '3']:

This should help various type checkers who will warn if there are
paths that can be taken that break this rule.

>   * GLFileSystem.py:166
>     def __init__(self, config: GLConfig, transformers: dict = dict()):
>     Is it possible to specify the key and value types of the last argument?

Oops, yes that was my intent but I seemed to have missed it on my
second pass over things. Good catch.

That is used for the 'sed' transformations created in
GLImport.prepare:

      # Determine script to apply to imported library files.
      sed_transform_lib_file = ''
      if 'config-h' in [ str(module)
                        for module in main_modules ]:
            sed_transform_lib_file += '''
        s/^#ifdef[\t ]*HAVE_CONFIG_H[\t ]*$/#if 1/
      '''
      # omitted code
      # Construct tables and transformers.
      transformers = dict()
      transformers['lib'] = sed_transform_lib_file
      transformers['aux'] = sed_transform_build_aux_file

Therefore it would be:

     def __init__(self, config: GLConfig, transformers: dict[str, str] = 
dict()):

You may find it more clear to change the default parameter assignment
'= dict()' to '= {}'.

Feel free to change that if you would like, though it will probably be
changed soon anyways. Since that is one of the 'sed' calls we want to
remove it might just be worth waiting until then.

The change from 'sed' to Python regular expressions would be easy in
that case. Instead of 'dict[str, str]' you could do
'dict[str, tuple[re.Pattern, str] | None]'

In that case None would be no transformations needed, and the tuple
would be parameters for re.sub():

    sed_transform_lib_file = (re.compile(r'^#ifdef[\t ]*HAVE_CONFIG_H[\t ]*$', 
re.MULTILINE), r'#if 1')

Not sure if all of that helped or made things more confusing, but feel
free to let me know if if you have any questions. :)

[1] https://docs.python.org/3/library/typing.html#the-any-type
[2] https://docs.python.org/3/library/typing.html#typing.Literal

Collin

Reply via email to