code: def load_packaged_grammar(
      package: str,
      grammar_source: str,
      cache_dir: Optional[Path] = None,
  ) -> grammar.Grammar:
      """Normally, loads a pickled grammar by doing
          pkgutil.get_data(package, pickled_grammar)
      where *pickled_grammar* is computed from *grammar_source* by adding the
      Python version and using a ``.pickle`` extension.
  
      However, if *grammar_source* is an extant file, load_grammar(grammar_source)
      is called instead. This facilitates using a packaged grammar file when needed
      but preserves load_grammar's automatic regeneration behavior when possible.
  
      """
      if os.path.isfile(grammar_source):
          gp = (
              _generate_pickle_name(grammar_source, cache_dir)
              if cache_dir
              else None
          )
          return load_grammar(grammar_source, gp=gp)
      pickled_name = _generate_pickle_name(
          os.path.basename(grammar_source), cache_dir
      )
      data = pkgutil.get_data(package, pickled_name)
      assert data is not None
      g = grammar.Grammar()
      g.loads(data)
      return g
  
imports: import io
  import logging
  import os
  import pkgutil
  import sys
  from contextlib import contextmanager
  from dataclasses import dataclass, field
  from logging import Logger
  from typing import IO, Any, Iterable, Iterator, List, Optional, Tuple, Union, cast
  from blib2to3.pgen2.grammar import Grammar
  from blib2to3.pgen2.tokenize import GoodTokenInfo
  from blib2to3.pytree import NL
  from .None import grammar, parse, pgen, token, tokenize
label_desc: Use image node_id 4 for calling a global function with example usage: load_packaged_grammar(package, grammar_source, cache_dir) and returns: g, load_grammar