On Fri, 2024-12-20 at 00:28 +0100, Scott Kostyshak wrote:
> On Thu, Dec 19, 2024 at 10:31:20PM +0000, José Matos wrote:
> > On Thu, 2024-12-19 at 15:57 +0100, Scott Kostyshak wrote:
> > > Is the problem that the object should not be a string?
> > 
> > Yes, it was expecting bytes.
> 
> Why not assert that at the beginning of the Python function?
> Or, what's the best way to do type-checking of arguments in Python?

This is an artifact of the joint support of Python 2 and Python 3.

https://docs.python.org/3.10/howto/pyporting.html

Python 3 distinguishes between binary format (bytes, bytesarray) and text (str).
You can convert from one to the other using an encoding.

Python 2 does not make this distinction, it is silent about.

I would say that most of the difficulties in ensuring that Python 2 and  Python
3 work are due to this aspect. In comparison all the other issues are minor.

Another important issue is that nowadays our files are utf-8 so that also
simplifies a lot the process.

So in lyxpak, and most of the other scripts, we should not be dealing with bytes
only text. Even if for some reason we deal initially with the binary we should
convert it as soon as possible to text and work from there.

That is the main strategy in the patch that I sent, the code should do what it
needs to read the file and then return text. So there should not be any need to
assert if the type is right.

In this case then this means that I have not ensured that this happens. So I
fixed one branch but there are others that need to be properly ported to this
scheme.


Regarding type checking in Python there are type annotations that are used to do
type hinting.

As an example take get_ert from lyx2lyx_tools.

Now we have:

def get_ert(lines, i, verbatim=False):
   ...

With type annotations we can have:

def get_ert(lines: list[str], i: int, verbatim:bool=False) -> list[str]:
   ...

This can be done from version 3.9, before we had to use this could be done using
stubs.

We can use the type annotations to catch some error types (at compile time and
not a run-time, because typing is optional) using external tools.

https://docs.python.org/3/library/typing.html

The type annotations are also used by text editors to ensure that the code is
correct, or at least flag possible problems.

Another important advantage of type annotations is that they improve the code
documentation. In the example above you see already that the first argument is
expected to be a list of strings and that it also returns a list of strings.


This is an area where more recent versions have better support.

In the next days I will try to look into your original problem to fix it.

Best regards,
-- 
José Abílio
-- 
lyx-devel mailing list
lyx-devel@lists.lyx.org
https://lists.lyx.org/mailman/listinfo/lyx-devel

Reply via email to