Dynamic typing

On this page 7

Dynamic typing is a property of a programming language in which types belong to values rather than to variables, and type compatibility is checked while the program runs instead of before it runs. In programming, languages such as Python, JavaScript, Ruby, PHP and Lisp are dynamically typed: a variable can hold an integer at one moment and a string the next, and an operation fails only when it is actually executed with unsuitable values.

Dynamic typing is the counterpart of static typing, where a compiler or checker verifies types before execution. The choice between them is a central design trade-off between flexibility and speed of writing code on one side and early error detection and tooling support on the other.

How dynamic typing works at run time

In a dynamically typed language, every value carries a type tag at run time. When the interpreter or virtual machine evaluates an expression such as a + b, it inspects the tags of both operands, selects the matching operation and raises a run-time type error if no valid operation exists. The variable names a and b themselves have no fixed type; they are simply references to tagged values.

This mechanism enables late binding: the method or operator that runs is chosen at the moment of the call. Many dynamic languages use duck typing, meaning that an object is acceptable if it provides the required methods, regardless of its declared class. Modern engines such as just-in-time compilers reduce the cost of these checks by observing which types actually appear and generating specialized machine code for them.

The following table contrasts what happens at each stage in a dynamically typed language.

StageWhat is known about typesTypical consequence
Writing codeOnly optional hints or commentsFast prototyping with little ceremony
Loading or parsingSyntax only, not type compatibilityType errors are not reported yet
ExecutionExact type of every valueErrors appear when the faulty line runs
Just-in-time compilationObserved types from profilingOptimized code with guard checks
Type handling across program stages

Dynamic typing compared with static typing

The difference between dynamic and static typing concerns when type errors are detected, not whether a language has types. Both approaches can be strict or permissive. Confusing dynamic with weak typing is one of the most common misconceptions: Python is dynamically but strongly typed, because it refuses to add a number to a string without an explicit conversion.

AspectDynamic typingStatic typing
Time of type checkingDuring executionBefore execution
Variable declarationsNo type requiredType declared or inferred
Error discoveryWhen the code path runsAt compile or check time
Refactoring supportLimited without annotationsStrong, tool-assisted
Run-time overheadType checks and tag storageMostly eliminated by the compiler
Typical languagesPython, JavaScript, RubyJava, C#, Rust, Go
Dynamic and static typing side by side

Static languages with type inference, such as Haskell or modern Java with var, can feel almost as concise as dynamic ones, which narrows the practical gap. Conversely, dynamic languages have added optional type hints, creating a middle ground.

Strong, weak and gradual variants

Dynamically typed languages differ in how readily they convert values implicitly. This axis is independent of the dynamic versus static question and strongly affects the kinds of bugs a developer encounters.

VariantBehaviorExample
Strong dynamic typingRejects mixing incompatible typesPython raises an error for 1 + "2"
Weak dynamic typingConverts values implicitlyJavaScript returns "12" for 1 + "2"
Gradual typingOptional annotations checked by toolsPython type hints, TypeScript over JavaScript
Optional static checkingSeparate checker analyzes annotated codemypy, Pyright, Sorbet for Ruby
Variants of dynamic typing

Gradual typing has become the dominant compromise in large codebases. Teams keep the flexibility of dynamic typing for scripts and exploratory work and add annotations to stable modules, so a checker can catch mismatched arguments and missing attributes before deployment.

Benefits and practical uses

Dynamic typing excels where speed of iteration matters more than formal guarantees. Data analysis, scripting, automation, prototyping and web back ends built on frameworks such as Django or Rails benefit from shorter code and immediate feedback in an interactive interpreter.

  • Less boilerplate: functions and containers work with any compatible value without generic declarations.
  • Interactive development: code can be tested line by line in a read-eval-print loop.
  • Metaprogramming: objects and classes can be inspected and modified at run time.
  • Flexible data handling: heterogeneous structures such as parsed JSON are easy to process.

The decision table below summarizes when dynamic typing is a sound default.

SituationRecommended approachReason
Short scripts and prototypesDynamic typingMinimal ceremony, fast feedback
Data exploration in notebooksDynamic typingInteractive, data-driven work
Large codebase with many teamsGradual or static typingSafer refactoring and clearer contracts
Performance-critical systems codeStatic typingPredictable speed and memory layout
Choosing a typing discipline

Limitations and common pitfalls

The main cost of dynamic typing is that type errors surface late, sometimes only in production when a rarely used branch finally runs. A misspelled attribute or a None value passed where an object was expected may remain hidden for months. Thorough automated tests are therefore not optional in dynamic codebases; they partly replace the guarantees a compiler would provide.

Performance is a second concern. Tag checks, boxed values and dictionary-based objects add overhead, so interpreted dynamic code is often one to two orders of magnitude slower than equivalent compiled static code for numeric loops, although just-in-time compilers and native libraries can close much of that gap. Finally, editors offer weaker autocompletion and navigation without type information, which slows work in unfamiliar code.

The short version

Picture a set of labeled boxes in a storage room. With dynamic typing, the boxes have no fixed label, and you can put a book in one today and a lamp in it tomorrow. Each item carries its own label instead.

The computer checks what is inside only when it needs to use it. That makes writing programs quick and flexible, but mistakes are found later, when the program actually reaches the wrong item.

Where it makes a difference

A data analyst writes a Python script to merge monthly sales files. Because of dynamic typing, she loads each CSV, adds columns and combines records in about forty lines of code, testing every step interactively in a notebook. The script works for eleven months of data.

In the twelfth month, one file contains the text N/A in a price column. The script fails at run time with a type error when it tries to add a number to that string, but only after processing several thousand rows. The team responds by adding type hints, running a static checker and writing a validation step that converts prices explicitly. The outcome is the same flexible script with an early safety net, which is the typical path from a dynamic prototype to maintained production code.