1515import contextlib
1616import datetime
1717import decimal
18+ import importlib
1819import inspect
1920import itertools
2021import json
2122import os
2223import pathlib
2324import re
2425import secrets
25- from sqlite_fts4 import rank_bm25 # type: ignore
26+ from sqlite_fts4 import rank_bm25
2627import textwrap
2728from typing import (
2829 cast ,
4344from sqlite_utils .plugins import pm
4445
4546try :
46- from sqlite_dump import iterdump # type: ignore[import-not-found]
47+ iterdump = importlib . import_module ( "sqlite_dump" ). iterdump
4748except ImportError :
4849 iterdump = None
4950
@@ -82,15 +83,17 @@ def quote_identifier(identifier: str) -> str:
8283 return '"{}"' .format (identifier .replace ('"' , '""' ))
8384
8485
86+ pd : Any = None
8587try :
86- import pandas as pd # type: ignore
88+ pd = importlib . import_module ( "pandas" )
8789except ImportError :
88- pd = None # type: ignore
90+ pd = None
8991
92+ np : Any = None
9093try :
91- import numpy as np # type: ignore
94+ np = importlib . import_module ( "numpy" )
9295except ImportError :
93- np = None # type: ignore
96+ np = None
9497
9598Column = namedtuple (
9699 "Column" , ("cid" , "name" , "type" , "notnull" , "default_value" , "is_pk" )
@@ -190,7 +193,10 @@ class Default:
190193
191194DEFAULT = Default ()
192195
193- COLUMN_TYPE_MAPPING = {
196+ Tracer = Callable [[str , Optional [Union [Sequence [Any ], Dict [str , Any ]]]], None ]
197+
198+
199+ COLUMN_TYPE_MAPPING : Dict [Any , str ] = {
194200 float : "REAL" ,
195201 int : "INTEGER" ,
196202 bool : "INTEGER" ,
@@ -339,7 +345,7 @@ def __init__(
339345 memory_name : Optional [str ] = None ,
340346 recreate : bool = False ,
341347 recursive_triggers : bool = True ,
342- tracer : Optional [Callable ] = None ,
348+ tracer : Optional [Tracer ] = None ,
343349 use_counts_table : bool = False ,
344350 execute_plugins : bool = True ,
345351 use_old_upsert : bool = False ,
@@ -375,8 +381,8 @@ def __init__(
375381 self .conn = sqlite3 .connect (str (filename_or_conn ))
376382 else :
377383 assert not recreate , "recreate cannot be used with connections, only paths"
378- self .conn = filename_or_conn
379- self ._tracer = tracer
384+ self .conn = cast ( sqlite3 . Connection , filename_or_conn )
385+ self ._tracer : Optional [ Tracer ] = tracer
380386 if recursive_triggers :
381387 self .execute ("PRAGMA recursive_triggers=on;" )
382388 self ._registered_functions : set = set ()
@@ -421,7 +427,7 @@ def ensure_autocommit_off(self) -> Generator[None, None, None]:
421427
422428 @contextlib .contextmanager
423429 def tracer (
424- self , tracer : Optional [Callable [[ str , Optional [ Sequence ]], None ] ] = None
430+ self , tracer : Optional [Tracer ] = None
425431 ) -> Generator ["Database" , None , None ]:
426432 """
427433 Context manager to temporarily set a tracer function - all executed SQL queries will
@@ -439,7 +445,7 @@ def tracer(
439445 :param tracer: Callable accepting ``sql`` and ``parameters`` arguments
440446 """
441447 prev_tracer = self ._tracer
442- self ._tracer = tracer or print
448+ self ._tracer = tracer or cast ( Tracer , print )
443449 try :
444450 yield self
445451 finally :
@@ -3493,7 +3499,7 @@ def insert_all(
34933499 raise ValueError (
34943500 "When using list-based iteration, the first yielded value must be a list of column name strings"
34953501 )
3496- column_names = list (first_record )
3502+ column_names = cast ( List [ str ], list (first_record ) )
34973503 all_columns = column_names
34983504 num_columns = len (column_names )
34993505 # Get the actual first data record
@@ -3535,7 +3541,8 @@ def insert_all(
35353541 chunk_as_dicts = [dict (zip (column_names , row )) for row in chunk ]
35363542 column_types = suggest_column_types (chunk_as_dicts )
35373543 else :
3538- column_types = suggest_column_types (chunk ) # type: ignore[arg-type]
3544+ dict_chunk = cast (List [Dict [str , Any ]], chunk )
3545+ column_types = suggest_column_types (dict_chunk )
35393546 if extracts :
35403547 for col in extracts :
35413548 if col in column_types :
@@ -3562,14 +3569,14 @@ def insert_all(
35623569 all_columns .insert (0 , hash_id )
35633570 else :
35643571 all_columns_set : Set [str ] = set ()
3565- for record in chunk :
3566- all_columns_set .update (record .keys ()) # type: ignore[union-attr]
3572+ for record in cast ( List [ Dict [ str , Any ]], chunk ) :
3573+ all_columns_set .update (record .keys ())
35673574 all_columns = list (sorted (all_columns_set ))
35683575 if hash_id :
35693576 all_columns .insert (0 , hash_id )
35703577 else :
35713578 if not list_mode :
3572- for record in chunk :
3579+ for record in cast ( List [ Dict [ str , Any ]], chunk ) :
35733580 all_columns += [
35743581 column for column in record if column not in all_columns
35753582 ]
@@ -3767,6 +3774,7 @@ def lookup(
37673774 :param strict: Boolean, apply STRICT mode if creating the table.
37683775 """
37693776 assert isinstance (lookup_values , dict )
3777+ assert pk is not None
37703778 if extra_values is not None :
37713779 assert isinstance (extra_values , dict )
37723780 combined_values = dict (lookup_values )
@@ -3786,7 +3794,7 @@ def lookup(
37863794 )
37873795 )
37883796 try :
3789- return rows [0 ][pk ] # type: ignore[index]
3797+ return rows [0 ][pk ]
37903798 except IndexError :
37913799 return self .insert (
37923800 combined_values ,
0 commit comments