code: def maybe_downcast_to_dtype(result, dtype):
      """try to cast to the specified dtype (e.g. convert back to bool/int
      or could be an astype of float64->float32
      """
  
      if is_scalar(result):
          return result
  
      def trans(x):
          return x
  
      if isinstance(dtype, string_types):
          if dtype == "infer":
              inferred_type = lib.infer_dtype(
                  ensure_object(result.ravel()), skipna=False
              )
              if inferred_type == "boolean":
                  dtype = "bool"
              elif inferred_type == "integer":
                  dtype = "int64"
              elif inferred_type == "datetime64":
                  dtype = "datetime64[ns]"
              elif inferred_type == "timedelta64":
                  dtype = "timedelta64[ns]"
  
              # try to upcast here
              elif inferred_type == "floating":
                  dtype = "int64"
                  if issubclass(result.dtype.type, np.number):
  
                      def trans(x):  # noqa
                          return x.round()
  
              else:
                  dtype = "object"
  
      if isinstance(dtype, string_types):
          dtype = np.dtype(dtype)
  
      try:
          # don't allow upcasts here (except if empty)
          if dtype.kind == result.dtype.kind:
              if result.dtype.itemsize <= dtype.itemsize and np.prod(
                  result.shape
              ):
                  return result
  
          if is_bool_dtype(dtype) or is_integer_dtype(dtype):
              # if we don't have any elements, just astype it
              if not np.prod(result.shape):
                  return trans(result).astype(dtype)
  
              # do a test on the first element, if it fails then we are done
              r = result.ravel()
              arr = np.array([r[0]])
  
              # if we have any nulls, then we are done
              if isna(arr).any() or not np.allclose(
                  arr, trans(arr).astype(dtype), rtol=0
              ):
                  return result
  
              # a comparable, e.g. a Decimal may slip in here
              elif not isinstance(
                  r[0],
                  (np.integer, np.floating, np.bool, int, float, bool),
              ):
                  return result
  
              if (
                  issubclass(result.dtype.type, (np.object_, np.number))
                  and notna(result).all()
              ):
                  new_result = trans(result).astype(dtype)
                  try:
                      if np.allclose(new_result, result, rtol=0):
                          return new_result
                  except Exception:
                      # comparison of an object dtype with a number type could
                      # hit here
                      if (new_result == result).all():
                          return new_result
          elif issubclass(
              dtype.type, np.floating
          ) and not is_bool_dtype(result.dtype):
              return result.astype(dtype)
  
          # a datetimelike
          # GH12821, iNaT is casted to float
          elif dtype.kind in ["M", "m"] and result.dtype.kind in [
              "i",
              "f",
          ]:
              try:
                  result = result.astype(dtype)
              except Exception:
                  if dtype.tz:
                      # convert to datetime and change timezone
                      from pandas import to_datetime
  
                      result = to_datetime(result).tz_localize("utc")
                      result = result.tz_convert(dtype.tz)
  
          elif dtype.type == Period:
              # TODO(DatetimeArray): merge with previous elif
              from pandas.core.arrays import PeriodArray
  
              return PeriodArray(result, freq=dtype.freq)
  
      except Exception:
          pass
  
      return result
  
imports: from datetime import datetime, timedelta
  import numpy
  from pandas._libs import lib, tslib, tslibs
  from pandas._libs.tslibs import NaT, OutOfBoundsDatetime, Period, iNaT
  from pandas.compat import PY3, string_types, text_type, to_str
  from .common import _INT64_DTYPE, _NS_DTYPE, _POSSIBLY_CAST_DTYPES, _TD_DTYPE, ensure_int8, ensure_int16, ensure_int32, ensure_int64, ensure_object, is_bool, is_bool_dtype, is_categorical_dtype, is_complex, is_complex_dtype, is_datetime64_dtype, is_datetime64_ns_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_datetimelike, is_dtype_equal, is_extension_array_dtype, is_extension_type, is_float, is_float_dtype, is_integer, is_integer_dtype, is_object_dtype, is_scalar, is_string_dtype, is_timedelta64_dtype, is_timedelta64_ns_dtype, is_unsigned_integer_dtype, pandas_dtype
  from .dtypes import DatetimeTZDtype, ExtensionDtype, PandasExtensionDtype, PeriodDtype
  from .generic import ABCDatetimeArray, ABCDatetimeIndex, ABCPeriodArray, ABCPeriodIndex, ABCSeries
  from .inference import is_list_like
  from .missing import isna, notna
label_desc: Use image node_id 3 for calling a global function with example usage: maybe_downcast_to_dtype(result, dtype) and returns: result, result, x, result, trans, result, result, result, new_result, PeriodArray, new_result, x