{"_id":"@amplication/python-ast","name":"@amplication/python-ast","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@amplication/python-ast","version":"0.1.0","description":"Python AST library in TypeScript","publishConfig":{"access":"public"},"dependencies":{"@amplication/ast-types":"*"},"main":"./src/index.js","type":"commonjs","types":"./src/index.d.ts","gitHead":"f61bd2f29ca640a001f12332af006ac6ccd7fc21","_id":"@amplication/python-ast@0.1.0","_nodeVersion":"18.17.0","_npmVersion":"9.6.7","dist":{"integrity":"sha512-VDc0sjShgFPb2sbHbguxwVpzxr9Hu3ZneUkwExT029SpyI5x7+ysLswhbe7FMrP/h8T/u5zmfdl8Tu6qynn0dQ==","shasum":"9003ae16746971b0bebb3a83962a30bce682b725","tarball":"https://registry.npmjs.org/@amplication/python-ast/-/python-ast-0.1.0.tgz","fileCount":47,"unpackedSize":76883,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCVD+pb78rp6eCaKlq9CZvbkiIHo0n8duSnBluXJdsAPQIgIEAOH3Fe/+aMqiz2iXsQMZxKELlSH/x1objWcxNvloY="}]},"_npmUser":{"name":"yuvalhazaz","email":"hazaz.yuval@gmail.com"},"directories":{},"maintainers":[{"name":"mulygottlieb","email":"muly@amplication.com"},{"name":"amplication-bot","email":"engineering@amplication.com"},{"name":"yuvalhazaz","email":"hazaz.yuval@gmail.com"},{"name":"morhag","email":"mor@amplication.com"},{"name":"levivannoort","email":"vanNoort.levi@protonmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/python-ast_0.1.0_1743415243773_0.6402040892600844"},"_hasShrinkwrap":false}},"time":{"created":"2025-03-31T10:00:43.630Z","0.1.0":"2025-03-31T10:00:43.971Z","modified":"2025-03-31T10:00:44.373Z"},"maintainers":[{"name":"mulygottlieb","email":"muly@amplication.com"},{"name":"amplication-bot","email":"engineering@amplication.com"},{"name":"yuvalhazaz","email":"hazaz.yuval@gmail.com"},{"name":"morhag","email":"mor@amplication.com"},{"name":"levivannoort","email":"vanNoort.levi@protonmail.com"}],"description":"Python AST library in TypeScript","readme":"# Python AST\n\nThis library provides an Abstract Syntax Tree (AST) representation for Python source code, focusing on the core language features necessary for defining classes, functions, and other declarations, while using a generic `CodeBlock` for unsupported language features.\n\n## Key Features\n\n- Core Python language constructs (modules, classes, functions)\n- Import management and type annotations\n- Generic code block for unsupported language features\n- Clean and consistent API that matches other Amplication AST libraries\n- Support for static and class methods\n- Async function support\n- Type hints and annotations\n\n## Installation\n\n```bash\nnpm install @amplication/python-ast\n```\n\n## Usage\n\n### Creating a Python Module with Imports\n\n```typescript\nimport { \n  Module,\n  Import,\n  ClassReference\n} from '@amplication/python-ast';\n\n// Create a module\nconst module = new Module({\n  name: 'user_service',\n});\n\n// Add imports\nmodule.addImport(new Import({\n  from: 'typing',\n  names: ['List', 'Optional']\n}));\n\nmodule.addImport(new Import({\n  from: 'datetime',\n  names: ['datetime']\n}));\n\n// Result:\n// from typing import List, Optional\n// from datetime import datetime\n```\n\n### Creating a Complete Python Class\n\n```typescript\nimport { \n  ClassDef, \n  FunctionDef, \n  Parameter, \n  ClassReference,\n  CodeBlock,\n  Module,\n  Decorator,\n  Return\n} from '@amplication/python-ast';\n\n// Create a class with inheritance\nconst userClass = new ClassDef({\n  name: 'User',\n  moduleName: 'models',\n  docstring: 'Represents a user in the system',\n  bases: [\n    new ClassReference({ name: 'BaseModel', moduleName: 'database.models' })\n  ]\n});\n\n// Add class attributes with type annotations\nuserClass.addAttribute(new CodeBlock({\n  code: 'created_at: datetime = datetime.now()'\n}));\n\n// Add constructor\nconst initMethod = new FunctionDef({\n  name: '__init__',\n  parameters: [\n    new Parameter({ name: 'self' }),\n    new Parameter({ \n      name: 'username', \n      type: new ClassReference({ name: 'str' })\n    }),\n    new Parameter({ \n      name: 'email', \n      type: new ClassReference({ name: 'str' })\n    }),\n    new Parameter({ \n      name: 'age', \n      type: new ClassReference({ name: 'Optional', genericTypes: [new ClassReference({ name: 'int' })] })\n    })\n  ],\n  docstring: 'Initialize a new User instance'\n});\n\ninitMethod.addStatement(new CodeBlock({\n  code: 'self.username = username\\nself.email = email\\nself.age = age'\n}));\n\nuserClass.addMethod(initMethod);\n\n// Add a static method\nconst createMethod = new FunctionDef({\n  name: 'create_user',\n  isStatic: true,\n  parameters: [\n    new Parameter({ \n      name: 'username', \n      type: new ClassReference({ name: 'str' })\n    }),\n    new Parameter({ \n      name: 'email', \n      type: new ClassReference({ name: 'str' })\n    })\n  ],\n  returnType: new ClassReference({ name: 'User' }),\n  docstring: 'Create a new user instance'\n});\n\ncreateMethod.addStatement(new CodeBlock({\n  code: 'user = User(username, email)\\nuser.save()\\nreturn user'\n}));\n\nuserClass.addMethod(createMethod);\n\n// Add an async method\nconst fetchDataMethod = new FunctionDef({\n  name: 'fetch_data',\n  isAsync: true,\n  parameters: [new Parameter({ name: 'self' })],\n  returnType: new ClassReference({ name: 'dict' }),\n  docstring: 'Fetch user data asynchronously'\n});\n\nfetchDataMethod.addStatement(new CodeBlock({\n  code: 'data = await api.get_user_data(self.username)\\nreturn data'\n}));\n\nuserClass.addMethod(fetchDataMethod);\n\n// Create a module and add the class\nconst module = new Module({ name: 'models' });\nmodule.addClass(userClass);\n\n// This will generate:\n/*\nfrom database.models import BaseModel\nfrom datetime import datetime\nfrom typing import Optional\n\nclass User(BaseModel):\n    \"\"\"Represents a user in the system\"\"\"\n    \n    created_at: datetime = datetime.now()\n    \n    def __init__(self, username: str, email: str, age: Optional[int]):\n        \"\"\"Initialize a new User instance\"\"\"\n        self.username = username\n        self.email = email\n        self.age = age\n    \n    @staticmethod\n    def create_user(username: str, email: str) -> \"User\":\n        \"\"\"Create a new user instance\"\"\"\n        user = User(username, email)\n        user.save()\n        return user\n    \n    async def fetch_data(self) -> dict:\n        \"\"\"Fetch user data asynchronously\"\"\"\n        data = await api.get_user_data(self.username)\n        return data\n*/\n```\n\n### Using CodeBlock for Unsupported Features\n\nThe `CodeBlock` class is useful for Python features not directly supported by the AST library:\n\n```typescript\n// Exception handling\nconst tryExceptBlock = new CodeBlock({\n  code: `\ntry:\n    result = process_data()\n    return result\nexcept ValueError as e:\n    logger.error(f\"Invalid data: {e}\")\n    raise\nfinally:\n    cleanup_resources()\n  `,\n  references: [\n    new ClassReference({ name: 'ValueError' }),\n    new ClassReference({ name: 'logger', moduleName: 'logging' })\n  ]\n});\n\n// Context managers\nconst withBlock = new CodeBlock({\n  code: `\nwith open(file_path, 'r') as file:\n    content = file.read()\n    process_content(content)\n  `\n});\n\n// Decorators with arguments\nconst decoratedMethod = new FunctionDef({\n  name: 'process_request',\n  decorators: [\n    new Decorator({\n      name: 'retry',\n      arguments: ['max_attempts=3', 'delay=1'],\n      moduleName: 'utils.decorators'\n    })\n  ]\n});\n```\n\n## API Reference\n\nThe library provides the following main components:\n\n- **Module**: Top-level container for Python code\n  - Manages imports and class definitions\n  - Handles module-level code organization\n\n- **ClassDef**: Class definition with methods and attributes\n  - Supports inheritance\n  - Manages class attributes and methods\n  - Handles docstrings and decorators\n\n- **FunctionDef**: Function or method definition\n  - Supports static and class methods\n  - Handles async functions\n  - Manages parameters and return types\n  - Supports decorators\n\n- **Parameter**: Function or method parameter\n  - Supports type annotations\n  - Handles default values\n  - Supports generic types\n\n- **Decorator**: Python decorator for functions/classes\n  - Supports decorator arguments\n  - Handles import management\n\n- **Import**: Import statement management\n  - Supports from-import statements\n  - Handles multiple imports\n  - Manages import aliases\n\n- **ClassReference**: Reference to a class\n  - Used for imports and type hints\n  - Supports generic types\n  - Handles module paths\n\n- **CodeBlock**: Generic container for unsupported features\n  - Allows raw Python code\n  - Manages dependencies through references\n  - Preserves formatting\n\n## Publishing\n\n## Publish to npm\n\nIn order to publish to npm `@amplication/python-ast` :\n\n1. Make sure to update the version in the package.json. \n2. Run the following:\n\n\n```sh\n# From the monorepo root folder\nnpm i\n\nnpx nx build python-ast\n\ncd ./dist/libs/python-ast\n\n```\n\nTo publish the package as \"beta\" run:\n\n```\nnpm publish --access public --tag beta\n```\n\nTo publish the package as \"latest\" run:\n\n```sh\n\nnpm publish --access public\n    \n```\n\n## License\n\nMIT ","readmeFilename":"README.md","_rev":"1-913fa030e73487cc52177ef0e7499cea"}