Type annotations: pathlib.Path vs importlib.resources.abc.Traversable

Advertisements When loading file resources that are bundled inside my distribution package, I use importlib.resources.files. When loading files from disk, I use pathlib.Path. Sometimes I want to write a function that will take either: from importlib.resources.abc import Traversable from pathlib import Path def process_file(file_to_process: Traversable | Path) -> None: … It feels cumbersome to annotate… Read More Type annotations: pathlib.Path vs importlib.resources.abc.Traversable

why does TemporaryDirectory change type within a "with" block?

Advertisements In python3 console >>> x1=tempfile.TemporaryDirectory() >>> print(type(x1)) <class ‘tempfile.TemporaryDirectory’> >>> with tempfile.TemporaryDirectory() as x2: … print(type(x2)) … <class ‘str’> Why is x1 a TemporaryDirectory and x2 a str? >Solution : Because with foo() as x has x take on the value of foo().__enter__()‘s return value. x = foo() is a different thing. See here… Read More why does TemporaryDirectory change type within a "with" block?

How can I convert base 10 integers to base 80 in Python without encountering IndexError?

Advertisements I’m working on a Python script where I need to convert base 10 integers to base 80 using a specific set of characters. I’ve implemented a function for this purpose, but I keep encountering an IndexError due to the index going out of range. Here’s the function I’m using: def base10_to_base80(n): base_80 = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~!$&\'()*+,:;=/’… Read More How can I convert base 10 integers to base 80 in Python without encountering IndexError?

Changing class attribute not working as expected

Advertisements Here is a simplified running code to show my problem: class c_event(): cl_attr = None def __init__(self, mystring): print(self.cl_attr) if self.cl_attr is None: self.cl_attr = mystring print(self.cl_attr) var1 = c_event(‘123’) var2 = c_event(‘456’) print(var1.cl_attr) print(var2.cl_attr) print(c_event.cl_attr) I am under the assumption that a class attribute defined like I did is common, read- and writeable… Read More Changing class attribute not working as expected

path syntax in python on windows for imports

Advertisements I have structured my python project on Windows so that Juypter notebooks are in there own folder. The paths are like this: \src\tracker\timer.py \notebooks\notebook_files.nypyb My import statement in the notebook_file used to look like: from timer import Timer But now this fails with import could not be resolved. I have tried various combinations to… Read More path syntax in python on windows for imports