Select to view content in your preferred language

What's in that module?

570
0
10-25-2021 05:23 PM
Labels (1)
DanPatterson
MVP Esteemed Contributor
0 0 570

I like to document, particular what is in a module/package that I am working on, or one that already exists.

Here are the results of the functions in my npg (NumPy Geometry) module.  I consists of separate scripts (modules) each containing a number of functions.

get_module_info(npg)

:-----------------------------------------------------------------:

Package: npg
File: C:\arcpro_npg\npg\__init__.py

Functions/methods:
_add_pnts_on_line_, _adj_, _angles_3pnt_, _append_fields, _area_centroid_,
_as_pivot, _bit_area_, _bit_check_, _bit_crossproduct_, _bit_length_,
_bit_min_max_, _bit_segment_angles_, _ch_, _ch_scipy_, _ch_simple_,
_check_dtype_, _closest_pnt_on_poly_, _dist_along_, _dist_arr_, _e_2d_,
_e_dist_, _field_specs, _fill_fields, _fill_float_array, _from_to_pnts_,
_get_base_, _get_numeric_fields, _in_LBRT_, _in_extent_, _intersect_,
_is_ccw_, _is_clockwise_, _is_convex_, _is_pnt_on_line_, _is_right_side,
_isin_2d_, _od_angles_dist_, _partition_, _percent_along_, _perp_,
_pnt_on_segment_, _pnts_in_extent_, _prn, _rotate_, _scale_, _svg,
_to_lists_, _trans_rot_, _translate_, _unique1d_, _utils_help_,
_view_as_struct_, _wrapper, _x_sect_2, Geo_to_arrays, Geo_to_lists, a_eq_b,
adjacency_matrix, adjacent, append_, arc_, arc_sector, array_IFT,
arrays_to_Geo, base_spiral, bin_pnts, calc_stats, cartesian_product,
center, check_geometry, circ_3p, circ_3pa, circle, circle_mini,
circle_ring, closest_n, code_grid, coerce2array, col_stats, common_extent,
common_pnts, compare_geom, concave, connect, crossing_num, crossings,
crosstab_array, crosstab_rc, crosstab_tbl, densify_by_distance,
densify_by_factor, dirr, dissolve, dist_angle_sort, distance, distances,
doc_func, dtype_info, ellipse, eucl_dist, .... snip ....
Classes :
CH, Delaunay, Geo

Members:

( 1) : np
package: numpy
( 2) : npGeo
_angles_3pnt_, _area_centroid_, _bit_area_, _bit_crossproduct_,
_bit_length_, _bit_min_max_, _fill_float_array, _rotate_, Geo_to_arrays,
Geo_to_lists, array_IFT, arrays_to_Geo, check_geometry, dedent, dirr,
indent, is_Geo, polyline_angles, reindex_shapes, repack_fields,
roll_coords, uniq_1d, uts, wrap
( 3) : npg
_add_pnts_on_line_, _adj_, _angles_3pnt_, _append_fields, _area_centroid_,
_as_pivot, _bit_area_, _bit_check_, _bit_crossproduct_, _bit_length_,
_bit_min_max_, _bit_segment_angles_, _ch_, _ch_scipy_, _ch_simple_,
_check_dtype_, _closest_pnt_on_poly_, _dist_along_, _dist_arr_, _e_2d_,
_e_dist_, _field_specs, _fill_fields, _fill_float_array, _from_to_pnts_,
_get_base_, _get_numeric_fields, _in_LBRT_, _in_extent_, _intersect_,
_is_ccw_, _is_clockwise_, _is_convex_, _is_pnt_on_line_, _is_right_side,
_isin_2d_, _od_angles_dist_, _partition_, _percent_along_, _perp_,
_pnt_on_segment_, _pnts_in_extent_, _prn, _rotate_, _scale_, _svg,
_to_lists_, _trans_rot_, _translate_, _unique1d_, _utils_help_,
_view_as_struct_, _wrapper, _x_sect_2, Geo_to_arrays, Geo_to_lists, a_eq_b,
adjacency_matrix, adjacent, append_, arc_, arc_sector, array_IFT,
arrays_to_Geo, base_spiral, bin_pnts, calc_stats, cartesian_product,
center, check_geometry, circ_3p, circ_3pa, circle, circle_mini,
circle_ring, closest_n, code_grid, coerce2array, col_stats, common_extent,
common_pnts, compare_geom, concave, connect, crossing_num, crossings,
crosstab_array, crosstab_rc, crosstab_tbl, densify_by_distance,
densify_by_factor, dirr, dissolve, dist_angle_sort, distance, distances,
doc_func, dtype_info, ellipse, eucl_dist, .... snip ....
( 4) : npgDocs
_update_docstring
( 5) : npg_analysis
_demo, _dist_arr_, _e_dist_, _x_sect_2, closest_n, concave, connect,
dedent, distances, intersection_pnt, knn, knn0, mst, n_check, n_near,
n_spaced, not_closer
( 6) : npg_arc_npg
_array_to_poly_, _fc_as_narray_, _fc_geo_interface_, _fc_shapes_,
_json_geom_, _poly_arr_, _poly_to_array_, _to_ndarray, AddField,
CopyFeatures, CreateFeatureclass, Delete, Describe, Exists,
Geo_to_arc_shapes, Geo_to_fc, array_poly, fc2na, fc_data, fc_dissolve,
fc_to_Geo, fc_union, geometry_fc, get_SR, get_shape_K, id_fr_to,
make_nulls, poly2array, repack_fields, shp_dissolve, stu, tbl_data,
view_poly
( 7) : npg_clip
_clp_, _wn_clip_, common_extent, plot_polygons, poly_clip, reverse_whr,
to_struct, uniq_1d, uniq_2d
( 😎 : npg_create
_test_data, arc_, arc_sector, arrays_to_Geo, base_spiral, circ_3p,
circ_3pa, circle, circle_mini, circle_ring, code_grid, ellipse,
from_spiral, hex_flat, hex_pointy, mesh_xy, mini_weave, plot_mixed,
pnt_from_dist_bearing, pyramid, rectangle, repeat, rot_matrix,
spiral_archim, spiral_ccw, spiral_cw, spiral_sqr, to_spiral,
transect_lines, triangle, xy_grid
( 9) : npg_geom
_add_pnts_on_line_, _angles_3pnt_, _bit_area_, _bit_min_max_, _ch_,
_ch_scipy_, _ch_simple_, _closest_pnt_on_poly_, _dist_along_, _e_2d_,
_get_base_, _in_extent_, _is_pnt_on_line_, _percent_along_,
_pnt_on_segment_, _view_as_struct_, bin_pnts, common_extent,
densify_by_distance, densify_by_factor, eucl_dist, extent_to_poly,
find_closest, in_hole_check, mabr, np_wn, offset_buffer, pnts_in_pnts,
pnts_on_poly, pnts_to_extent, polys_to_segments, polys_to_unique_pnts,
repack_fields, scale_by_area, segments_to_polys, simplify_lines, stu,
triangulate_pnts, uts
(10) : npg_helpers
_angles_3pnt_, _area_centroid_, _bit_area_, _bit_check_,
_bit_crossproduct_, _bit_length_, _bit_min_max_, _bit_segment_angles_,
_from_to_pnts_, _get_base_, _in_LBRT_, _in_extent_, _is_ccw_,
_is_clockwise_, _is_convex_, _is_right_side, _isin_2d_, _iterate_,
_od_angles_dist_, _perp_, _pnts_in_extent_, _rotate_, _scale_, _to_lists_,
_trans_rot_, _translate_, a_eq_b, cartesian_product, coerce2array,
common_pnts, compare_geom, dist_angle_sort, flat, interweave, keep_geom,
polyline_angles, prn_tbl, project_pnt_to_line, radial_sort, reclass_ids,
remove_geom, segment_angles, shape_finder, sort_xy, stride_2d, uniq_1d,
uniq_2d, uts
(11) : npg_io
dtype_info, geojson_Geo, load_geo, load_geojson, load_txt, save_geo,
save_txt
(12) : npg_min_circ
center, circle_mini, distance, farthest, small_circ, sub_1, sub_2
(13) : npg_overlay
_adj_, _bit_check_, _in_LBRT_, _intersect_, _line_crossing_, _to_lists_,
adjacency_matrix, adjacent, append_, crossings, dissolve, in_out_crosses,
intersections, intersects, left_right_pnts, line_crosses, line_side,
merge_, np_wn, p_ints_p, pnt_segment_info, radial_sort, remove_geom,
union_as_one
(14) : npg_pip
_is_right_side, _partition_, crossing_num, np_wn, pnts_in_Geo, winding_num
(15) : npg_plots
_demo, _get_cmap_, axis_mins_maxs, plot_2d, plot_3d, plot_mesh, plot_mixed,
plot_mst, plot_polygons, scatter_params, subplts
(16) : npg_prn
_ckw_, _col_format, _svg, col_hdr, dedent, gms, indent, make_row_format,
prn_, prn_Geo_shapes, prn_arrays, prn_as_obj, prn_geo, prn_lists, prn_q,
prn_tbl, stu
(17) : npg_setops
_check_dtype_, _unique1d_, _view_as_struct_, nd_diff, nd_diffxor, nd_in1d,
nd_intersect, nd_isin, nd_merge, nd_union, nd_uniq
(18) : npg_table
_append_fields, _as_pivot, _field_specs, _fill_fields, _get_numeric_fields,
_prn, calc_stats, col_stats, crosstab_array, crosstab_rc, crosstab_tbl,
dedent, find_a_in_b, find_in, group_sort, group_stats, keep_fields_by_kind,
keep_fields_by_name, merge_arrays, n_largest_vals, n_smallest_vals,
nd2struct, remove_seq_dupl, running_count, sequences, split_sort_slice,
struct2nd
(19) : npg_utils
_utils_help_, _wrapper, dedent, dir_py, doc_deco, doc_func, env_list,
find_def, folders, get_dir, get_func, get_module_info, indent, run_deco,
sub_folders, time_deco, wrap

 

 

 

 

 

def get_module_info(obj, max_number=100, verbose=True):
    """Get module (script) information, including source code if needed.

    Parameters
    ----------
    obj : module (script)
        The imported object.  It must be either a whole module or a script
        that you imported.  Import it. It is easier if it is in the same
        folder as the script running this function.
    verbose : boolean
        True, prints the output.  False, returns the string.

    Requires
    --------
      >>> from textwrap import dedent, indent
      >>> import inspect

    Returns
    -------
    A string is returned for printing.  It will be the whole module
    so use with caution.

    Example
    -------
    Importing this function from the following module to inspect the module
    itself.

    >>> from npgeom.npg_utils import get_module_info
    >>> get_module_info(npg, False, True)
    >>> # No quotes around module name, code=True for module code
    """
    def wrapit(_in, counter=None):
        """Wrap a string."""
        nmes = _in[1]
        if len(nmes) > max_number:
            nmes = nmes[:max_number] + [".... snip ...."]
        sub = ", ".join([j for j in nmes])
        sub = wrap(sub, 75)
        txt = "\n".join([j for j in sub])
        if counter is None:
            return "\n{}\n{}".format(i[0], indent(txt, "    "))
        s = "\n({:2.0f}) : {}\n{}".format(counter, i[0], indent(txt, "    "))
        return s
    # ----
    ln = "\n:{}:\n\n".format("-" * 65)
    f1 = "{}Package: {}\nFile:    {}"
    import inspect
    from textwrap import indent, wrap
    if not inspect.ismodule(obj):
        out = "\nError... `{}` is not a module, but is of type... {}\n"
        print(out.format(obj.__name__, type(obj)))
        return None
    # ----
    path_parts = obj.__file__.split("\\")[:-1]
    mod_path = "\\".join([i for i in path_parts])
    out = []
    mem = inspect.getmembers(obj, inspect.ismodule and not inspect.isbuiltin)
    func = inspect.getmembers(obj, inspect.isroutine)  # isfunction)
    clas_ = inspect.getmembers(obj, inspect.isclass)
    _a0 = sorted([i[0] for i in func if i[0].startswith("_")])  # dir(m[1])
    _a1 = sorted([i[0] for i in func if not i[0].startswith("_")])  # dir(m[1])
    _all = _a0 + _a1
    _c0 = sorted([i[0] for i in clas_])
    out.append(["Functions/methods:", _all])
    out.append(["Classes :", _c0])
    out.append(["\nMembers:", ""])
    for m in mem:
        if hasattr(m[1], "__file__"):
            if mod_path in m[1].__file__:
                r = inspect.getmembers(m[1], inspect.isroutine)
                _a = [i[0] for i in r]
                _a0 = sorted([i for i in _a if i.startswith("_")])
                _a1 = sorted([i for i in _a if not i.startswith("_")])
                _all = _a0 + _a1
                out.append([m[0], _all])
            else:
                out.append([m[0], ["package: {}".format(m[1].__package__)]])
    # ----
    s = ""
    for i in out[:3]:
        s += wrapit(i, counter=None)
    cnt = 1
    for i in out[3:]:
        s += wrapit(i, counter=cnt)
        cnt += 1
    args0 = [ln, obj.__name__, obj.__file__]
    p0 = f1.format(*args0)
    if verbose:
        print("{}\n{}".format(p0, s))
        # print(s)
    else:
        return "{}\n{}\n".format(p0, s)

 

 

 

Just don't try it on arcpy... you will have to limit the output.  In this case 25 functions maximum per file

get_module_info(arcpy, 25, True)

:-----------------------------------------------------------------:

Package: arcpy
File: C:\arc_pro\Resources\ArcPy\arcpy\__init__.py

Functions/methods:
_ClearCredentials, _ImportCredentials, _NumPyArrayToRaster,
_RasterToNumPyArray, _SignInToPortal, _gptooldoc, ASCII3DToFeatureClass_3d,
ASCIIToRaster_conversion, AcceptConnections, Add3DFormats_management,
AddAngleDirectedLayout_nd, AddAngleDirectedLayout_un,
AddAttachments_management, AddAttributeRule_management,
AddAviationLineBypass_aviation, AddCADFields_conversion,
AddCodedValueToDomain_management, AddCollapseContainerByAttributeRule_nd,
AddCollapseContainerByAttributeRule_un, AddCollapseContainerRule_nd,
AddCollapseContainerRule_un, AddColormap_management,
AddCompressionLayout_nd, AddCompressionLayout_un,
AddConnectivityAssociationsRule_nd, .... snip ....
Classes :
Annotation, ArcSDESQLExecute, Array, Chart, CrossValidationResult, Cursor,
Dimension, EnvManager, ExecuteError, ExecuteWarning, Extent, FeatureSet,
Field, FieldInfo, FieldMap, FieldMappings, Filter, GeoProcessor, Geometry,
Index, Mensuration, Multipatch, Multipoint, NetCDFFileProperties,
Parameter, .... snip ....

Members:

( 1) : _base
_ValidateParameter
( 2) : _colorizer
convertArcObjectToPythonObject, gp_fixargs, pass_parameterized_attr,
passthrough_attr
( 3) : _ga
_ValidateParameter, GeostatisticalDatasets
( 4) : _geocoding

( 5) : _mp
PDFDocumentCreate, PDFDocumentOpen, convertArcObjectToPythonObject,
gp_fixargs, passthrough_attr
( 6) : _na
CheckIntersectingFeatures, ConvertStringToFloat, CreateTrafficIndex,
ExportRouteData, GenerateDirectionsFeatures, GetNAClassNames,
GetNASublayer, GetSolverProperties, GetTravelModes, GetWebToolInfo,
IsNetworkDatasetBuilt, ListDirectionsLanguages, ListDirectionsStyleNames,
SelectNetworkDataset, UpdateLiveTrafficFeedLocation
( 7) : _renderer
convertArcObjectToPythonObject, gp_fixargs, pass_parameterized_attr,
passthrough_attr
( 😎 : _symbology
convertArcObjectToPythonObject, gp_fixargs, pass_parameterized_attr,
passthrough_attr
( 9) : _utbx
_internal, _is_toolbox_path, CreateTool, CreateToolbox, Delete, DeleteTool,
GetProps, ImportTool, Rename, SetProps
(10) : _wmx
Connect, convertArcObjectToPythonObject, gp_fixargs, passthrough_attr
(11) : agolservices
FindClosestFacilities, FindRoutes, GenerateOriginDestinationCostMatrix,
GenerateServiceAreas, Profile, SolveLocationAllocation,
SolveVehicleRoutingProblem, SummarizeElevation, TraceDownstream, Viewshed,
Watershed
(12) : analysis
ApportionPolygon, Buffer, Clip, CountOverlappingFeatures,
CreateThiessenPolygons, Enrich, EnrichLayer, Erase, Frequency,
GenerateNearTable, GenerateOriginDestinationLinks,
GeographicallyWeightedRegression, GraphicBuffer, Identity, Intersect,
MultipleRingBuffer, Near, PairwiseBuffer, PairwiseClip, PairwiseDissolve,
PairwiseErase, PairwiseIntegrate, PairwiseIntersect, PointDistance,
PolygonNeighbors, .... snip ....
(13) : arcobjectconversion
convertArcObjectToPythonObject, initialize_conversion_mapping
(14) : arcobjects
convertArcObjectToPythonObject, passthrough_attr
(15) : arcpy
_ClearCredentials, _ImportCredentials, _NumPyArrayToRaster,
_RasterToNumPyArray, _SignInToPortal, _gptooldoc, ASCII3DToFeatureClass_3d,
ASCIIToRaster_conversion, AcceptConnections, Add3DFormats_management,
AddAngleDirectedLayout_nd, AddAngleDirectedLayout_un,
AddAttachments_management, AddAttributeRule_management,
AddAviationLineBypass_aviation, AddCADFields_conversion,
AddCodedValueToDomain_management, AddCollapseContainerByAttributeRule_nd,
AddCollapseContainerByAttributeRule_un, AddCollapseContainerRule_nd,
AddCollapseContainerRule_un, AddColormap_management,
AddCompressionLayout_nd, AddCompressionLayout_un,
AddConnectivityAssociationsRule_nd, .... snip ....

....... BIG SNIP 

(70) : utils
_fetchvar, _fix_paraminfo_item, _fixedwhitespace, _fixline,
_get_lines_with_prototype, _mergelines, _pick_names, _textwrap,
arg_index_for_call_string, call_ranges, code_diff_report, code_to_python_3,
fetchautocomplete, find_autocomplete_candidates, find_autocomplete_xml,
fixdocstring, function_call_in_context, get_all_fix_names,
get_index_and_argvals_for_dropdown_call, getstartingpage, help_tip,
inProcess, in_index, listofnamedtuples, logcall, .... snip ....
(71) : warnings
package:
(72) : wmx
ClearJobReplicationInfo, Connect, CreateJobDataReplica, CreateJobs,
CreateNewJobs, CreateWorkflowDatabase, ExportJobData, GetJobAOI,
GetJobDataWorkspace, GetJobParentVersion, GetJobVersion, ImportJobData,
PostJobVersion, PublishWorkflowService, SynchronizeJobData,
UpgradeWorkflowDatabase

 

 

About the Author
Retired Geomatics Instructor (also DanPatterson_Retired). Currently working on geometry projects (various) as they relate to GIS and spatial analysis. I use NumPy, python and kin and interface with ArcGIS Pro.
Labels