Home > Mobile >  General Syntaxe pythonquestion : from typed language to untyped one
General Syntaxe pythonquestion : from typed language to untyped one

Time:09-23

I'am new to python language. And my question is certainly a naive one and concerne python syntaxe.

I am a the step where I must go from theory to practice.

here is a class (a typescript one) I want to translate to python language.

class Category {
    id: number;
    type: 'shop'|'blog';
    name: string;
    slug: string;
    path: string;
    image: string|null;
    items: number;
    customFields: CustomFields;
    parents?: Category[]|null;
    children?: Category[]|null;
}

as python is untyped language I've got doubts about how to translate :

  • the optional property : '?'
  • the associated class : customFields: CustomFields;
  • the arrays of associated class (that are self associated) and that are nullable : children?: Category[]|null;

I've always worked with typed language until now and it's destabilisising my habits to just write nothing.

would that look like this (it's a model for django.db migration):

>from django.db import models

    >>class Category(models.Model):
    >>>    id = models.AutoField(primary_key=True)
    >>>   type: 'shop'|'blog'
    >>>    name = models.CharField(max_length=100)
    >>>    slug = models.CharField(max_length=100)
    >>>    path = models.CharField(max_length=250)

and then ... ?

could you provide also some tuto, doc, example where you learn python in pratice ? thanks to all of you !

CodePudding user response:

When you define a function in Python you can enforce static typing but its not necessary. In case you need to have a static typing enforced you can do something like this.

//for functions
def addition(a: int, b: int) -> int:
    return a   b
addition(4,10)

//For Variables or attributes
name: str = 'test'
age: int = 10
rating: float = 1.11
is_exist: bool = True

There are more things found in python documentation related to typing in case you can refer documentation.

CodePudding user response:

If you must enforce typing in your Python code, take a look at isinstance.
For optional Class attributes in Python, you can use keyword arguments as shown in this answer.

CodePudding user response:

it's best to learn the language by following the documentation for it, there are enough examples in the documentation. https://docs.python.org/3/

If you want to learn Django, there are quite a lot of tutorials. But first of all, look here. https://docs.djangoproject.com/en/3.2/

As for your example with the Category Class The id is determined automatically and it is not necessary to explicitly specify it in the model, see more https://docs.djangoproject.com/en/3.2/topics/db/models/

  • Related