Skip to content

rework public Languages API fixes #4494 - #4496

Merged
pekkaklarck merged 19 commits into
robotframework:masterfrom
d-biehl:rework_of_languages_api
Oct 11, 2022
Merged

pekkaklarck merged 19 commits into
robotframework:masterfrom
d-biehl:rework_of_languages_api

Conversation

@d-biehl

@d-biehl d-biehl commented Oct 5, 2022

Copy link
Copy Markdown
Contributor

Example of a better public Languages API

d-biehl and others added 3 commits October 5, 2022 06:36
@d-biehl

d-biehl commented Oct 5, 2022

Copy link
Copy Markdown
Contributor Author

How can I rerun the checks or/and download the artifacts of the failed runs?
I cannot reproduce the errors on my local machine. And I'm not able to download the artifact off failed checks, to get the real error messages

@d-biehl

d-biehl commented Oct 5, 2022

Copy link
Copy Markdown
Contributor Author

ok, I got it.

@pekkaklarck pekkaklarck left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks very good. Apart from smallish style issues, the only thing I think that should be changed is the return value of import_language_module. Or do you have a strong reason for returning a dict of classes instead of a list of instances like earlier?

Comment thread src/robot/conf/languages.py Resolved
Comment thread src/robot/conf/languages.py Resolved
Comment thread utest/api/test_languages.py Resolved
Comment thread src/robot/conf/languages.py Resolved
@d-biehl
d-biehl requested a review from pekkaklarck October 10, 2022 14:22
Comment thread src/robot/conf/languages.py Resolved
Comment thread src/robot/conf/languages.py Resolved
Comment thread src/robot/conf/languages.py Resolved
@pekkaklarck

Copy link
Copy Markdown
Member

Changes look good now (apart from unused DataError import and some unnecessary empty lines in code and unit tests), but I still don't understand the need to change the return type of import_language_module from a list of instances to a dictionary of classes where same class can occur multiple times in values. Is there some reason for that?

@d-biehl

d-biehl commented Oct 10, 2022

Copy link
Copy Markdown
Contributor Author

import_language_module returns the same things like get_available_languages but only for a module. One entry for the code and one entry for the name of language from doc.

@pekkaklarck

Copy link
Copy Markdown
Member

I got that but why? It makes our code more complicated. Does it help in some external usage?

@d-biehl

d-biehl commented Oct 10, 2022

Copy link
Copy Markdown
Contributor Author

Yes, it helps, with that it is possible to use the same mechanism to select the possible language class that needs to be instanciated as if we use get_available_languages. Or To update the results from import_language_module with import_language_module
like this:

langs = Languages.get_available_languages()
for m in lang_modules:
   langs.update(Languages.import_language_module(import_language_module)

@pekkaklarck

Copy link
Copy Markdown
Member

The point of import_language_module is to import a module and return languages there. Returning a dict where the same language can be twice doesn't make sense for me.

The point of get_available_languages is to return all available languages. To ease checking is certain language available, it returns a dict where language codes and names are keys and same language can appear twice. I don't see why these two methods should both return a dict. If returning same type would be considered important, I don't see why it would be, then they both could return a list.

It would make sense for these two methods to consistently return either classes or instances, though. I don't have strong preference either way. If they'd return classes, then we should enhance Language.code/name propertys so that they'd work also with classes. Python unfortunately doesn't allow stacking @classmethod and @property, but it's easy to create a custom @classproperty decorator for this purpose. I can do that.

@pekkaklarck

Copy link
Copy Markdown
Member

Is there a reason you need to use

langs = Languages.get_available_languages()
for m in lang_modules:
   langs.update(Languages.import_language_module(m)

instead of

for m in lang_modules:
   Languages.import_language_module(m)
langs = Languages.get_available_languages()

?

@d-biehl

d-biehl commented Oct 10, 2022

Copy link
Copy Markdown
Contributor Author

Yes it is, because I want to be as close as possible to the robotframework implementation and the language argument is either a language name or a language code or module name. So I have to look in available languages if there is name or code otherwise I have to import the language and look there, if I found something, I can add the result of my available languages instead of calling get_available_languages again.

@pekkaklarck

pekkaklarck commented Oct 10, 2022 •

Copy link
Copy Markdown
Member

So your use case is something like this:

available = Languages.get_available_languages()
for lang in languages:
    if lang not in available:
        available.update(Languages.import_language_module(lang))

How's that better than the following?

available = Languages(languages).get_available_languages()

@pekkaklarck

Copy link
Copy Markdown
Member

It should also be decided should get_available_languages return language codes with or without possible hyphen. We have, for example PtBr that has code pt-BR. In the current implementation _get_available_languages doesn't use the hyphen which is fine in internal usage, but in a public method I believe the hyphen should be there. Similarly we need to decide are codes and names case and space normalized or not.

This makes me think should this method really be public or not. Perhaps it would be better if external users just used list(Languages(...)) to get language instances and then used them as needed. If there's a need to check is a language available, we could then add something like Languages.get_language() that would accept language code, w/ or w/o hyphen, or name as an argument the same way as Language.from_name(). Not sure would Languages.get_language() be that useful when we already have Language.from_name(), though.

@pekkaklarck

pekkaklarck commented Oct 10, 2022 •

Copy link
Copy Markdown
Member

The more I think about this, the less I see real needs to expose get_available_languages publicly when list(Languages(...)) already works. Could you explain the use case for it? If it only simplifies some use case a little, and doesn't allow some new use case, then I think we should keep it private. I'm fairly certain we need to enhance Languages in future releases and the smaller public API it has, the easier it is to change.

I'm not sure is exposing import_language_module publicly needed either when just passing all languages to Languages() when you initialize it works as well. Not needing to recreate the instance if new language modules are to be loaded would be convenient, though, but the current implementation of import_language_module doesn't actually do that. I think it would be better to enhance the current add_language so that it works also with language modules. Do you have some concrete use cases where import_language_module would be better?

Controlling is English loaded or not is definitely a useful enhancement.

@d-biehl

d-biehl commented Oct 10, 2022 •

Copy link
Copy Markdown
Contributor Author

Ok, example:

The user defines these languages (see code) in the settings of VSCode. I want to load all languages that i can load. Independent of whatever happens, wrong syntax, the pythonpath ist not correct or whatever, I want to load all Languages I can and for the languages that I cannot load RobotCode should give an error in the problems tab.

Here the code (it's copied from robotcode, but simplified to be runnable)

from typing import List
from robot.conf.languages import Languages
from robot.utils.normalizing import normalize
from robot.errors import DataError

languages = ["fi", "pt-BR", "wr-ONG", "de", "CustomLang", "Chinese Traditional"]

available_languages = Languages.get_available_languages()
diagnostics: List[str] = []

found_languages: List[str] = []
for lang in languages:
    normalized_lang = normalize(lang, "-")

    language = available_languages.get(normalized_lang, None)
    if language is None:
        try:
            available_languages.update(Languages.import_language_module(lang))
            language = available_languages.get(normalized_lang, None)
        except DataError:
            pass
    if language is None:
        diagnostics.append(f"{lang} is not a valid language definition or language module.")
    else:
        found_languages.append(lang)

print(diagnostics)
print(found_languages)

If I only have:

available = Languages(languages).get_available_languages()

I get an exceptions after the first wrong language, And I dont know where in the list of languages is the error.

@d-biehl

d-biehl commented Oct 10, 2022

Copy link
Copy Markdown
Contributor Author

And why I must create an instance of the Language class to get the available languages?
The actual implemention of _get_available_languages is defined as instance method, it defines self but did not use it.

@pekkaklarck

pekkaklarck commented Oct 10, 2022 •

Copy link
Copy Markdown
Member

Thanks for the example, it's very useful. Based on it seems that just enhancing Languages.add_language so that it works also with language modules would work and make the code a lot simpler:

from typing import List
from robot.api import Languages

languages = ["fi", "pt-BR", "wr-ONG", "de", "CustomLang", "Chinese Traditional"]
available = Languages()
diagnostics: List[str] = []

for lang in languages:
    try:
        available.add_language(lang)
    except ValueError as err:
        diagnostics.append(f"{lang} is not a valid language definition or language module.")

print(diagnostics)
print(list(available))

The above code already works otherwise, but custom language modules aren't supported. Enhancing add_language to support that is easy. Probably should then also change add_language to use DataError instead of ValueError because the former is used if importing a module fails. The above also loads English which isn't desired. Making that configurable is a totally non-controversial part of this PR although the argument name should probably be add_english and not add_default.

@pekkaklarck

Copy link
Copy Markdown
Member

You don't need to create an instance of Language or Languages to get available languages. You can simply call Language.__subclassess__() that's already public.

@pekkaklarck

pekkaklarck commented Oct 10, 2022 •

Copy link
Copy Markdown
Member

Are there some other use case where making English optional and enhancing add_language as discussed above wouldn't be enough? If not, I'd say that's the approach to use. I already tested that enhancing add_language is easy:

    def add_language(self, name):
        """Add new language.

        :param name: Name or code of a language to add, or name or path of
                     a language file to load.
        :raises: :class:`~robot.errors.DataError` if language not found.

        Language codes and names are passed to by :meth:`Language.from_name`.
        Language files are imported as modules and :class:`Language` subclasses
        in them are loaded.
        """
        try:
            languages = [Language.from_name(name)]
        except ValueError as err1:
            try:
                languages = self._import_languages(name)
            except DataError as err2:
                raise DataError(f'{err1} {err2}')
        for lang in languages:
            self._add_language(lang)

If you agree on this approach, we can decide who finishes this work. You've already spent lot of time with the PR and it contains good docs and tests and it would be great if you could finalize it. If you don't have time or interest, I can do that as well. It's clear we won't get rc 2 out today, but I hope we'd get it out tomorrow.

@d-biehl

d-biehl commented Oct 10, 2022

Copy link
Copy Markdown
Contributor Author

Ok, see my comment in the issue ;-)

Even if I think (please do not be angry) we could do better ;-) Can I finalize the PR, but only tomorrow evening. If too late for you, ... let's talk tommorow.

@pekkaklarck

Copy link
Copy Markdown
Member

If enhancing add_language and not exposing new methods is fine for you, I can take your PR and do those changes. I can either continue with the PR or just merge it and continue from there. As I commented the issue, I'd like to keep the API small now because it needs to be enhanced in the future anyway. More convenience can be added later when the API is more stable.

If you have time, it would be awesome if you could look at #4497. I got an implementation for that ready and can commit if it is considered good enough.

@d-biehl
d-biehl requested a review from pekkaklarck October 11, 2022 05:42
@d-biehl

d-biehl commented Oct 11, 2022

Copy link
Copy Markdown
Contributor Author

ok, implemented your add_language proposal, but move get_available_languages and import_language_module to the global namespace, so that these functions are not public api, but because in robotcode I use already the not public api it's my turn if something changed.
What about this.

I missed 1 unittest will fix this later when I'm back from the doctor....

@pekkaklarck

Copy link
Copy Markdown
Member

No, I don't want these methods to be in the module scope as public functions either. That makes no sense from Robot's point of view and I don't want to make them public as a convenience for external tools because it adds maintenance burden for us. I've told that multiple times. My position is not going to change unless you have a concrete example where these methods are needed and don't only avoid you writing a line or two more code on RobotCode side.

This issue has now delayed RF 6.0 so long that I really need to get it closed. Are you willing to revert your changes related to making these two methods public? If yes, and you can do that pretty soon today, I can still wait for that. Otherwise I can do the following API changes myself:

  • Make English optional.
  • Enhance add_language to work with language modules.

@pekkaklarck
pekkaklarck merged commit 09ca68f into robotframework:master Oct 11, 2022
@pekkaklarck

Copy link
Copy Markdown
Member

After latest changes this looks very good! There are few more things that I think can be enhanced listed below but I can take care of them:

  • API docs to add_language
  • Changing the exception that add_language can raise to DataError to match the exception you can get when you initialize Languages.
  • Make Language.code/name class propertys to allow using them also when working with Langugage classes, not only with instances.

@d-biehl

d-biehl commented Oct 11, 2022

Copy link
Copy Markdown
Contributor Author

You were too fast ;-) I just optimized a little bit and merged duplicate codes. And the add_language also allows to add a language instance.

Maybe we can merge that too. Do I have to open a new PR for this?

@d-biehl

d-biehl commented Oct 11, 2022

Copy link
Copy Markdown
Contributor Author

Parser "needs" a ValueError thats why I leave it so. CommandLine Option needs a DataError to get the correct error text.

pekkaklarck added a commit that referenced this pull request Oct 11, 2022
- More doc strings.
- Change exception used by `Languages.add_language` on error to match
  exception used when initializing `Languages`.
- Make `Language.code/name` propertys accessible also from class.
  This required implementing new `@classproperty` decorator.

This is part of issue #4494 and the work was started in #4496.
@pekkaklarck

Copy link
Copy Markdown
Member

I don't see the final changes you mentioned anywhere. Were there other new features than add_language accepting Language instances? I can add that myself. Since this PR is already merged, let's use the issue for discussion about possible changes.

@d-biehl

d-biehl commented Oct 11, 2022

Copy link
Copy Markdown
Contributor Author

See here d-biehl@fa63db3

Because the PR was closed, it is not shown there. I did not have the time this evening to make a new PR, but maybe you see what I did.
Mainly add_language does the same as get_languages. I extract the same parts to a new method.

@pekkaklarck

Copy link
Copy Markdown
Member

I added support for using Language instances with add_language. Other changes didn't seem to add new functionality.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants