Python Peculiarities

satya - 1/2/2022, 9:17:13 AM

First set: syntactical

1. type less

2. implied string concatenation

3. brackets essential in functions

4. semicolon optional (for multiple lines)

5. semicolon to separate multiple statements on the same line

6. filename can have any extension (although .py is common)

satya - 1/2/2022, 10:00:19 AM

Symbols 2

The colon ":"

The under score "__Somefunc__"

The tab

satya - 3/3/2024, 3:42:02 PM

Python has the following buil in functions

  1. list()
  2. tuple()
  3. set()
  4. len()
  5. bool()
  6. int()
  7. float()
  8. complex()

satya - 3/6/2024, 4:27:40 PM

Sometimes pylance grows crazy over types

  1. As you start using libraries, all of them may not specify type hints to their code
  2. This causes problems when you start using strict typing
  3. One example is say you have a dictionary of strings and objects and you are passing to a function that has no type hints
  4. This seem to throw off pylance pretty badly
  5. You can turn this off by typing #type:ignore on that line

satya - 3/6/2024, 4:28:24 PM

An example


def _getFlattenedDictionary(tomlConfigFilename: str) -> dict[str, Any]:
    # Read and parse the toml file
    toml_str = fileutils.read_text_file(tomlConfigFilename)
    parsed_toml: tomlkit.TOMLDocument = tomlkit.parse(toml_str)
    # convert it to json
    json_str: str = json.dumps(parsed_toml,indent=4)
    dict = json.loads(json_str)
    new_dict = _process_dict_for_aliases(dict)

    flat_dict = flatten(new_dict, reducer="dot") #type:ignore
    return flat_dict #type:ignore

satya - 3/9/2024, 9:34:33 AM

Defining optional arguments


Using Union
****************************
from typing import Union
def my_function(value: Union[str, None]) -> Union[str, None]:
    return value

From 3.10
****************************
def my_function(value: str | None) -> str | None:
    return value

Using Optional
*********************
from typing import Optional
def my_function(value: Optional[str]) -> Optional[str]:
    return value

Probably Prefered
*********************
Use the | approach
For it requires no imports

satya - 3/9/2024, 9:49:50 AM

An example


def opArgFunction(arg1: str, arg2: str | None = None):
    log.ph1("Op args")
    log.info(arg1)
    if not arg2 is None:
        log.info(arg2)