Skip to content

Workaround for Pyscript Importing Folder by Compiling Wheel ​

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

Why ​

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

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

The below script will result in error.

xml
<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.

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

But it breaks package.

Workaround ​

Pyscript provide another method: Importing a wheel

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

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

Structure ​

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

Compile wheel ​

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

python
import setuptools

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

After compiling wheel:

bash
python3 setup.py build bdist_wheel

We can find wheel file is generate in dist folder:

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

Include and Use ​

pyscript.json:

json

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

index.html:

xml
<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 ​

Changelog

Just observe 👀