Skip to content

Commit

Permalink
Add some explanations for isinstance()
Browse files Browse the repository at this point in the history
Reviewed By: JakobDegen

Differential Revision: D63813312

fbshipit-source-id: 93c09649fbe8af3dc2f90764f3114785e92bcfa0
  • Loading branch information
stepancheg authored and facebook-github-bot committed Oct 3, 2024
1 parent 4d71985 commit 9efb6ca
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions starlark/src/values/typing/type_compiled/globals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,21 @@ pub(crate) fn register_eval_type(globals: &mut GlobalsBuilder) {
}

/// Check if a value matches the given type.
///
/// This operation can be very fast or very slow depending on how it is used.
///
/// `isinstance(x, list)` is very fast,
/// because it is compiled to a special bytecode instruction.
///
/// `isinstance(x, list[str])` is `O(N)` operation
/// because it checks every element in this list.
///
/// `L = list; [isinstance(x, L) for x in y]` is slow when `L` is not a constant:
/// `isinstance()` first converts `list` to a type in a loop, which is slow.
///
/// But last operation can be optimized like this:
/// `L = eval_type(list); [isinstance(x, L) for x in y]`:
/// `eval_type()` converts `list` value into prepared type matcher.
fn isinstance<'v>(
#[starlark(require = pos)] value: Value<'v>,
#[starlark(require = pos)] ty: ValueOfUnchecked<'v, AbstractType>,
Expand Down

0 comments on commit 9efb6ca

Please sign in to comment.