Workaround for Pyscript Importing Folder by Compiling Wheel

·

1 min read

2024/03/24: Updated for new version of py-config

Why

Currently, we cannot import a folder of python package in pyscript, for example:

├── index.html
├── myapp8763
│   ├── init.py
│   └── funcs.py

The below script will result in error.

<py-script>
  import myapp8763.funcs # can't find package myapp8763
  myapp8763.funcs.main()
</py-script>

The user can only import single file and use it like importing a single file.

<py-script>    
  import funcs
  funcs.main()
</py-script>

But it breaks package.

Workaround

Pyscript provide another method: Importing a wheel

{
    "packages": ["./dist/myapp8763-0.0.1-py3-none-any.whl"]
}

If we want to import a folder, we should compile a wheel file.

Structure

.
├── index.html
├── myapp8763
│   ├── init.py
│   └── funcs.py
└── setup.py

Compile wheel

To compile a package as a wheel, we need setup.py:

import setuptools

setuptools.setup(
    name='myapp8763',
    version='0.0.1',
    packages=setuptools.find_packages('.'),
    package_dir={
        'myapp8763': 'myapp8763',
    },
    setup_requires=['wheel'],
)

After compiling wheel:

python3 setup.py build bdist_wheel

We can find wheel file is generate in dist folder:

├── dist
│   └── myapp8763-0.0.1-py3-none-any.whl

Include and Use

pyscript.json:


{
    "packages": ["./dist/myapp8763-0.0.1-py3-none-any.whl"]
}

index.html:

<script type="py" config="./pyscript.json">
  import myapp8763.funcs
  myapp8763.funcs.main()
</script>

Code

The whole code is here: https://github.com/mudream4869/pyscript-local-package

Ref