How to create virtual environment with conda

Conda is an open-source package management system and virtual environment management system that runs on Windows, macOS, and Linux. It was created for Python programs but it can package and distribute software for any language such as R, Ruby, Lua, Scala, Java, JavaScript, C, C++, FORTRAN.

The two main purposes of Conda are:

  1. Package management: Conda makes it easy to manage and install packages, even for different versions of Python. In addition, it also supports binary package management, which makes it an efficient way to handle packages and dependencies in your projects.
  2. Virtual Environment management: Conda allows you to create separate environments containing files, packages, and their dependencies that will not interact with other environments. When switching between Python versions for different projects, Conda makes it simple to use the specific version you need.

While pip can install Python packages, Conda can install packages for any language. Conda packages are binaries, which eliminates the need to compile the code which makes installations faster and more straightforward.

Installing conda

$ brew update
$ brew install --cask miniconda

Checking conda version

$ conda --version

conda 23.3.1

Conda help

$ conda -h
usage: conda [-h] [-V] command ...

conda is a tool for managing and deploying applications, environments and packages.


positional arguments:
    clean             Remove unused packages and caches.
    compare           Compare packages between conda environments.
    config            Modify configuration values in .condarc. This is modeled after the git config command. Writes to the
                      user .condarc file (/Users/kenanhancer/.condarc) by default. Use the --show-sources flag to display
                      all identified configuration locations on your computer.
    create            Create a new conda environment from a list of specified packages.
    info              Display information about current conda install.
    init              Initialize conda for shell interaction.
    install           Installs a list of packages into a specified conda environment.
    list              List installed packages in a conda environment.
    package           Low-level conda package utility. (EXPERIMENTAL)
    remove (uninstall)
                      Remove a list of packages from a specified conda environment. Use `--all` flag to remove all packages
                      and the environment itself.
    rename            Renames an existing environment.
    run               Run an executable in a conda environment.
    search            Search for packages and display associated information.The input is a MatchSpec, a query language for
                      conda packages. See examples below.
    update (upgrade)  Updates conda packages to the latest compatible version.
    notices           Retrieves latest channel notifications.

  -h, --help          Show this help message and exit.
  -V, --version       Show the conda version number and exit.

conda commands available from other packages (legacy):
Continue reading

How to create virtual environment with pipenv

Pipenv is a Python tool that aims to bring the best features of multiple other tools into one. It provides an easy way to manage virtual environments and manage package dependencies consistently. Its key goal is to simplify the workflow of managing a Python environment for your project.

Installing pipenv

$ python -m pip install pipenv

Checking pipenv version

$ pipenv --version

pipenv, version 2022.7.4

Checking pipenv version

$ pipenv -h
Usage: pipenv [OPTIONS] COMMAND [ARGS]...

  --where                         Output project home information.
  --venv                          Output virtualenv information.
  --py                            Output Python interpreter information.
  --envs                          Output Environment Variable options.
  --rm                            Remove the virtualenv.
  --bare                          Minimal output.
  --man                           Display manpage.
  --support                       Output diagnostic information for use in
                                  GitHub issues.
  --site-packages / --no-site-packages
                                  Enable site-packages for the virtualenv.
                                  [env var: PIPENV_SITE_PACKAGES]
  --python TEXT                   Specify which version of Python virtualenv
                                  should use.
  --three                         Use Python 3 when creating virtualenv.
  --clear                         Clears caches (pipenv, pip).  [env var:
  -q, --quiet                     Quiet mode.
  -v, --verbose                   Verbose mode.
  --pypi-mirror TEXT              Specify a PyPI mirror.
  --version                       Show the version and exit.
  -h, --help                      Show this message and exit.

Usage Examples:
   Create a new project using Python 3.7, specifically:
   $ pipenv --python 3.7

   Remove project virtualenv (inferred from current directory):
   $ pipenv --rm

   Install all dependencies for a project (including dev):
   $ pipenv install --dev

   Create a lockfile containing pre-releases:
   $ pipenv lock --pre

   Show a graph of your installed dependencies:
   $ pipenv graph

   Check your installed dependencies for security vulnerabilities:
   $ pipenv check

   Install a local into your virtual environment/Pipfile:
   $ pipenv install -e .

   Use a lower-level pip command:
   $ pipenv run pip freeze

  check         Checks for PyUp Safety security vulnerabilities and against
                PEP 508 markers provided in Pipfile.
  clean         Uninstalls all packages not specified in Pipfile.lock.
  graph         Displays currently-installed dependency graph information.
  install       Installs provided packages and adds them to Pipfile, or (if no
                packages are given), installs all packages from Pipfile.
  lock          Generates Pipfile.lock.
  open          View a given module in your editor.
  requirements  Generate a requirements.txt from Pipfile.lock.
  run           Spawns a command installed into the virtualenv.
  scripts       Lists scripts in current environment config.
  shell         Spawns a shell within the virtualenv.
  sync          Installs all packages specified in Pipfile.lock.
  uninstall     Uninstalls a provided package and removes it from Pipfile.
  update        Runs lock, then sync.
  verify        Verify the hash in Pipfile.lock is up-to-date.
Continue reading

How to create virtual environment with pyenv-virtualenv plugin

pyenv-virtualenv is a pyenv plugin that provides features to manage virtualenvs and conda environments for Python on UNIX-like systems.

If you don't have pyenv in your system, follow below post;

Installing pyenv-virtualenv

$ brew update
$ brew install pyenv-virtualenv

Setting PATH

Run one of the following commands in terms of your shell's .rc file.

$ echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc
$ echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.zshrc

Creating virtual environment

$ mkdir python_demo
$ cd python_demo
$ pyenv install 3.11.4
$ pyenv virtualenv 3.11.4 python_demo-3.11.4
$ pyenv virtualenvs
$ pyenv prefix python_demo-3.11.4
$ ls -Llat $(pyenv prefix python_demo-3.11.4)

drwxr-xr-x  14 kenanhancer  staff  448 19 Jun 17:36 bin
-rw-r--r--   1 kenanhancer  staff  107 19 Jun 17:36 pyvenv.cfg
drwxr-xr-x   3 kenanhancer  staff   96 19 Jun 17:36 lib
drwxr-xr-x   2 kenanhancer  staff   64 19 Jun 17:36 include
$ tree -a -L 4 $(pyenv prefix python_demo-3.11.4)

├── bin
│   ├── Activate.ps1
│   ├── activate
│   ├── activate.csh
│   ├──
│   ├── pip
│   ├── pip3
│   ├── pip3.11
│   ├── pydoc
│   ├── python -> python3.11
│   ├── python3 -> python3.11
│   └── python3.11 -> /Users/kenanhancer/.pyenv/versions/3.11.4/bin/python3.11
├── include
│   └── python3.11
├── lib
│   └── python3.11
│       └── site-packages
│           ├── _distutils_hack
│           ├── distutils-precedence.pth
│           ├── pip
│           ├── pip-23.1.2.dist-info
│           ├── pkg_resources
│           ├── setuptools
│           └── setuptools-65.5.0.dist-info
└── pyvenv.cfg
Continue reading

TypeScript const assertions vs satisfies operator

I compare as const assertions and satisfies operator in this post.

as const comes with TypeScript 3.4 and generates literal values for more precise and type-safe code.

satisfies comes with TypeScript 4.9 and generates more specific type and validates given object type so that it can catch possible error.

Notice that as const generates a type with readonly fields. So it is an immutable type.

Use case

Notice that satisfies just generates a type from palette object. As you can see below code, red field type is [number, number, number]

As you can see below code, red field type became string instead of [number, number, number]

Use case

satisfies operator catches unlisted field name usage, or wrong field type.

TypeScript const modifier on type parameters

It is a really good feature coming with TypeScript 5.0. We could infer type of object as general as shown in line 8 in below code, so, to infer more-specific type, we had to add as const as shown in line 11.

TypeScript 5.0 makes it easier with adding const in front of type parameter declaration in line 13 in below code.

Use case

Assume that Person type has hobbies , and i just want to infer passed values from hobbies field.

TypeScript Union Type and Distributive Conditional Types Part 2

I show the reason Distributive Conditional Type needs to be used for Union Type in this post.

If generic type T is passed as Union Type like string | number, then array item will be Union Type as below.

If you need to iterate on each type in Union Type, then Distributive Conditional Type (with extends keywod) needs to be used.

To avoid distributive behaviour in Distibutive Conditional Type, surround each side of extends keyword with square brackets.

Continue reading

How to install Python packages with pipenv, venv or virtualenv package manager

You can find GitHub repository in

  • Pyenv – Python Runtime Version Manager
    – to install, uninstall, list or switch between different python runtimes
  • Pipenv – Python Package Manager and Virtual environment manager
    – to create an isolated virtual environment with a specific python runtime
    – to install, uninstall, list python packages
  • Venv – Virtual environment manager (for Python 3)
    – to create an isolated virtual environment with a specific python runtime
    – python packages will be isolated already
  • Virtualenv – Virtual environment manager (for Python 2)
    – to create an isolated virtual environment with a specific python runtime
    – python packages will be isolated already

Installing Python Runtime Versions via Pyenv

In order to test different Python Runtime versions, I have installed some versions.

$ pyenv install 3.10.2
$ pyenv install 3.10.3
$ pyenv install 3.10.4
$ pyenv install 3.10.5

I have 4 Python runtime versions(3.10.2, 3.10.3, 3.10.4, 3.10.5) in my machine. So, let's list them.

$ pyenv versions

* 3.10.5 (set by /Users/kenanhancer/.pyenv/version)
Continue reading

TypeScript Recursive Type

Below two code blocks are doing same job and the only difference is below second code block uses variadic tuple. Check the below links for more details.

type CompareLength<Left extends any[], Right extends any[]> =
    Left['length'] extends Right['length'] ? 'equal' :
    Left extends [] ? 'shorterLeft' :
    Right extends [] ? 'shorterRight' :
    ((..._: Left) => any) extends ((_: any, ..._1: infer LeftRest) => any) ?
    ((..._: Right) => any) extends ((_: any, ..._1: infer RightRest) => any) ?
    CompareLength<LeftRest, RightRest> :
    never :

type T1 = CompareLength<[firstName: string], [lastName: string]>;

type T2 = CompareLength<[firstName: string], [lastName: string, age: number]>;

type T3 = CompareLength<[firstName: string, age: number], [lastName: string]>;
type CompareLength<Left extends any[], Right extends any[]> =
    Left['length'] extends Right['length'] ? 'equal' :
    Left extends [] ? 'shorterLeft' :
    Right extends [] ? 'shorterRight' :
    Left extends [any, ...infer L] ? 
    Right extends [any, ...infer R] ? 
    CompareLength<L, R> :
    never :

type T1 = CompareLength<[firstName: string], [lastName: string]>;

type T2 = CompareLength<[firstName: string], [lastName: string, age: number]>;

type T3 = CompareLength<[firstName: string, age: number], [lastName: string]>;

TypeScript Exhaustiveness Checking Part 2

type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";

const sendRequest = (url: string, method: HttpMethod) => {
    switch (method) {
        case 'DELETE':

        case 'GET':

        case 'POST':

        case 'PUT':

            const exhaustiveCheck: never = method; // ✅ no error
            throw new Error(`Unhandled case: ${exhaustiveCheck}`);
type Fruit = 'banana' | 'orange' | 'mango';

function exhaustiveCheck(param: never): never {
    throw new Error('should not reach here')

function makeDessert(fruit: Fruit) {
    switch (fruit) {
        case 'banana': return 'Banana Shake'
        case 'orange': return 'Orange Juice'
    exhaustiveCheck(fruit) // ? ERROR! `mango` is not assignable
Continue reading

TypeScript Exhaustiveness Checking

Exhaustiveness checking is a good feature when you use switch block. Assume that you need to check a value of variable which data type is union type as shown below screenshot.

Shape is a discriminated union which consists of three types named Circle, Square and Triangle.

kind field is shared in Circle, Square and Triangle types so that if developer forgets to use any of kind field value in switch block, TypeScript will error in coding-time.

Notice that there is a red line in line 347, it is due to missing triangle case in switch block.

This is the error shown in the code.

After adding triangle case in line 346, the error disappeared.

Continue reading