Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(pacmak): Generate Relative Module Imports in Python #3181

Merged
merged 4 commits into from
Nov 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion packages/jsii-pacmak/lib/targets/python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
PythonImports,
mergePythonImports,
toPackageName,
toPythonFqn,
} from './python/type-name';
import { die, toPythonIdentifier } from './python/util';
import { toPythonVersionRange, toReleaseVersion } from './version-utils';
Expand Down Expand Up @@ -1673,7 +1674,26 @@ class PythonModule implements PythonType {
for (const module of this.modules.sort((l, r) =>
l.pythonName.localeCompare(r.pythonName),
)) {
code.line(`import ${module.pythonName}`);
// Rather than generating an absolute import like
// "import jsii_calc.submodule.nested_submodule.deeply_nested"
// this builds a relative import like
// "from .submodule.nested_submodule import deeply_nested"
// This enables distributing python packages and using the
// generated modules in the same codebase.
const assemblyName = toPythonFqn(
module.assembly.name,
module.assembly,
).pythonFqn;

const submodule = module.pythonName
.replace(`${assemblyName}.`, '')
.split('.');

const submodulePath = submodule
.slice(0, submodule.length - 1)
.join('.');
const submoduleName = submodule[submodule.length - 1];
code.line(`from .${submodulePath} import ${submoduleName}`);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jsii-pacmak/lib/targets/python/type-name.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ class UserType implements TypeName {
}
}

function toPythonFqn(fqn: string, rootAssm: Assembly) {
export function toPythonFqn(fqn: string, rootAssm: Assembly) {
const { assemblyName, packageName, tail } = getPackageName(fqn, rootAssm);
const fqnParts: string[] = [packageName];

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.