From 6afdf59aea63217a6f8430a5aff82b7e856856be Mon Sep 17 00:00:00 2001 From: Franz Weitkamp Date: 2019年9月27日 22:44:15 +0200 Subject: [PATCH 1/8] Use comprehension, prevent unnecessary lists, use more generators --- .../chart-studio/chart_studio/api/v2/utils.py | 2 +- .../dashboard_objs/dashboard_objs.py | 4 +-- .../chart_studio/grid_objs/grid_objs.py | 8 ++--- .../chart_studio/plotly/plotly.py | 2 +- .../presentation_objs/presentation_objs.py | 10 ++----- .../test_plot_ly/test_image/test_image.py | 2 +- .../python/chart-studio/chart_studio/utils.py | 5 +--- .../plotly/_plotly_utils/basevalidators.py | 8 ++--- .../plotly/_plotly_utils/colors/__init__.py | 10 ++----- packages/python/plotly/codegen/figure.py | 2 +- packages/python/plotly/plotly/_version.py | 6 ++-- .../python/plotly/plotly/basedatatypes.py | 20 +++++-------- .../figure_factory/_annotated_heatmap.py | 4 +-- .../figure_factory/_county_choropleth.py | 4 +-- .../plotly/plotly/figure_factory/_gantt.py | 29 ++++--------------- .../plotly/plotly/figure_factory/_ohlc.py | 4 +-- .../plotly/figure_factory/_scatterplot.py | 12 ++------ .../plotly/plotly/figure_factory/_trisurf.py | 12 ++------ .../plotly/plotly/figure_factory/_violin.py | 19 +++--------- .../plotly/plotly/figure_factory/utils.py | 8 ++--- packages/python/plotly/plotly/io/_orca.py | 8 ++--- .../plotly/plotly/matplotlylib/mpltools.py | 6 ++-- .../plotly/plotly/matplotlylib/renderer.py | 8 ++--- packages/python/plotly/plotly/subplots.py | 8 ++--- .../test_update_objects/test_update_traces.py | 2 +- packages/python/plotly/versioneer.py | 6 ++-- 26 files changed, 63 insertions(+), 146 deletions(-) diff --git a/packages/python/chart-studio/chart_studio/api/v2/utils.py b/packages/python/chart-studio/chart_studio/api/v2/utils.py index 4c02295729..805b44d934 100644 --- a/packages/python/chart-studio/chart_studio/api/v2/utils.py +++ b/packages/python/chart-studio/chart_studio/api/v2/utils.py @@ -75,7 +75,7 @@ def validate_response(response): if isinstance(parsed_content, dict): errors = parsed_content.get("errors", []) messages = [error.get("message") for error in errors] - message = "\n".join([msg for msg in messages if msg]) + message = "\n".join(msg for msg in messages if msg) if not message: message = content if content else "No Content" diff --git a/packages/python/chart-studio/chart_studio/dashboard_objs/dashboard_objs.py b/packages/python/chart-studio/chart_studio/dashboard_objs/dashboard_objs.py index ca2d2ea059..81db46a14f 100644 --- a/packages/python/chart-studio/chart_studio/dashboard_objs/dashboard_objs.py +++ b/packages/python/chart-studio/chart_studio/dashboard_objs/dashboard_objs.py @@ -296,9 +296,7 @@ def _make_all_nodes_and_paths(self): all_nodes.sort(key=lambda x: x[1]) # remove path 'second' as it's always an empty box - all_paths = [] - for node in all_nodes: - all_paths.append(node[1]) + all_paths = [node[1] for node in all_nodes] path_second = ("second",) if path_second in all_paths: all_paths.remove(path_second) diff --git a/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py b/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py index 39f1f1b6a9..c82897f9f3 100644 --- a/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py +++ b/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py @@ -164,9 +164,7 @@ def __init__(self, columns_or_json, fid=None): raise exceptions.InputError(err) # create columns from dataframe - all_columns = [] - for name in columns_or_json.columns: - all_columns.append(Column(columns_or_json[name].tolist(), name)) + all_columns = [Column(columns_or_json[name].tolist(), name) for name in columns_or_json.columns] self._columns = all_columns self.id = "" @@ -199,9 +197,7 @@ def __init__(self, columns_or_json, fid=None): ) # collect and sort all orders in case orders do not start # at zero or there are jump discontinuities between them - all_orders = [] - for column_name in columns_or_json["cols"].keys(): - all_orders.append(columns_or_json["cols"][column_name]["order"]) + all_orders = [columns_or_json["cols"][column_name]["order"] for column_name in columns_or_json["cols"].keys()] all_orders.sort() # put columns in order in a list diff --git a/packages/python/chart-studio/chart_studio/plotly/plotly.py b/packages/python/chart-studio/chart_studio/plotly/plotly.py index 2df1bb5ad0..2258c1895f 100644 --- a/packages/python/chart-studio/chart_studio/plotly/plotly.py +++ b/packages/python/chart-studio/chart_studio/plotly/plotly.py @@ -1236,7 +1236,7 @@ def append_rows(cls, rows, grid=None, grid_url=None): v2.grids.row(fid, {"rows": rows}) if grid: - longest_column_length = max([len(col.data) for col in grid]) + longest_column_length = max(len(col.data) for col in grid) for column in grid: n_empty_rows = longest_column_length - len(column.data) diff --git a/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py b/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py index eee6616e08..464ce5276c 100644 --- a/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py +++ b/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py @@ -352,10 +352,7 @@ def _list_of_slides(markdown_string): text_blocks = re.split("\n-{2,}\n", markdown_string) - list_of_slides = [] - for text in text_blocks: - if not all(char in ["\n", "-", " "] for char in text): - list_of_slides.append(text) + list_of_slides = [text for text in text_blocks if not all(char in ["\n", "-", " "] for char in text)] if "\n-\n" in markdown_string: msg = ( @@ -1040,10 +1037,7 @@ def _markdown_to_presentation(self, markdown_string, style, imgStretch): slide_trans = _remove_extra_whitespace_from_line( slide_trans ) - slide_transition_list = [] - for key in VALID_TRANSITIONS: - if key in slide_trans: - slide_transition_list.append(key) + slide_transition_list = [key for key in VALID_TRANSITIONS if key in slide_trans] if slide_transition_list == []: slide_transition_list.append("slide") diff --git a/packages/python/chart-studio/chart_studio/tests/test_plot_ly/test_image/test_image.py b/packages/python/chart-studio/chart_studio/tests/test_plot_ly/test_image/test_image.py index d9c5253c82..c5dd80e316 100644 --- a/packages/python/chart-studio/chart_studio/tests/test_plot_ly/test_image/test_image.py +++ b/packages/python/chart-studio/chart_studio/tests/test_plot_ly/test_image/test_image.py @@ -77,7 +77,7 @@ def _test(self): ]: _test = test_generator(*args) - arg_string = ", ".join([str(a) for a in args]) + arg_string = ", ".join(str(a) for a in args) test_name = test_generator.__name__.replace("_generate", "test") test_name += "({})".format(arg_string) setattr(TestImage, test_name, _test) diff --git a/packages/python/chart-studio/chart_studio/utils.py b/packages/python/chart-studio/chart_studio/utils.py index f2fc92c1c1..c8da3a059d 100644 --- a/packages/python/chart-studio/chart_studio/utils.py +++ b/packages/python/chart-studio/chart_studio/utils.py @@ -161,10 +161,7 @@ def validate_world_readable_and_sharing_settings(option_set): def validate_plotly_domains(option_set): - domains_not_none = [] - for d in ["plotly_domain", "plotly_api_domain"]: - if d in option_set and option_set[d]: - domains_not_none.append(option_set[d]) + domains_not_none = [option_set[d] for d in ["plotly_domain", "plotly_api_domain"] if d in option_set and option_set[d]] if not all(d.lower().startswith("https") for d in domains_not_none): warnings.warn(http_msg, category=UserWarning) diff --git a/packages/python/plotly/_plotly_utils/basevalidators.py b/packages/python/plotly/_plotly_utils/basevalidators.py index 0ade83a950..4f3208e558 100644 --- a/packages/python/plotly/_plotly_utils/basevalidators.py +++ b/packages/python/plotly/_plotly_utils/basevalidators.py @@ -1629,7 +1629,7 @@ def present(self, v): elif isinstance(v, string_types): return v else: - return tuple([tuple(e) for e in v]) + return tuple(tuple(e) for e in v) class AngleValidator(BaseValidator): @@ -1821,10 +1821,10 @@ def vc_scalar(self, v): split_vals = [e.strip() for e in re.split("[,+]", v)] # Are all flags valid names? - all_flags_valid = all([f in self.all_flags for f in split_vals]) + all_flags_valid = all(f in self.all_flags for f in split_vals) # Are any 'extras' flags present? - has_extras = any([f in self.extras for f in split_vals]) + has_extras = any(f in self.extras for f in split_vals) # For flaglist to be valid all flags must be valid, and if we have # any extras present, there must be only one flag (the single extras @@ -2705,7 +2705,7 @@ def validate_coerce(self, v, skip_invalid=False): # multiple template names joined on '+' characters elif isinstance(v, string_types): template_names = v.split("+") - if all([name in pio.templates for name in template_names]): + if all(name in pio.templates for name in template_names): return pio.templates.merge_templates(*template_names) except TypeError: diff --git a/packages/python/plotly/_plotly_utils/colors/__init__.py b/packages/python/plotly/_plotly_utils/colors/__init__.py index 2f344de3ea..d38329feaf 100644 --- a/packages/python/plotly/_plotly_utils/colors/__init__.py +++ b/packages/python/plotly/_plotly_utils/colors/__init__.py @@ -766,20 +766,14 @@ def colorscale_to_colors(colorscale): """ Extracts the colors from colorscale as a list """ - color_list = [] - for item in colorscale: - color_list.append(item[1]) - return color_list + return [item[1] for item in colorscale] def colorscale_to_scale(colorscale): """ Extracts the interpolation scale values from colorscale as a list """ - scale_list = [] - for item in colorscale: - scale_list.append(item[0]) - return scale_list + return [item[0] for item in colorscale] def convert_colorscale_to_rgb(colorscale): diff --git a/packages/python/plotly/codegen/figure.py b/packages/python/plotly/codegen/figure.py index ab1e1c9b74..97cca5a6c9 100644 --- a/packages/python/plotly/codegen/figure.py +++ b/packages/python/plotly/codegen/figure.py @@ -67,7 +67,7 @@ def build_figure_py( buffer.write(f"from plotly.{base_package} import {base_classname}\n") # ### Import trace graph_obj classes ### - trace_types_csv = ", ".join([n.name_datatype_class for n in trace_nodes]) + trace_types_csv = ", ".join(n.name_datatype_class for n in trace_nodes) buffer.write(f"from plotly.graph_objs import ({trace_types_csv})\n") # Write class definition diff --git a/packages/python/plotly/plotly/_version.py b/packages/python/plotly/plotly/_version.py index e3f8c5bd62..d27705754d 100644 --- a/packages/python/plotly/plotly/_version.py +++ b/packages/python/plotly/plotly/_version.py @@ -186,11 +186,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print ("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = set(r.strip() for r in refnames.strip("()").split(",")) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) + tags = set(r[len(TAG) :] for r in refs if r.startswith(TAG)) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -199,7 +199,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r"\d", r)]) + tags = set(r for r in refs if re.search(r"\d", r)) if verbose: print ("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: diff --git a/packages/python/plotly/plotly/basedatatypes.py b/packages/python/plotly/plotly/basedatatypes.py index a423ae1197..aa334c1a96 100644 --- a/packages/python/plotly/plotly/basedatatypes.py +++ b/packages/python/plotly/plotly/basedatatypes.py @@ -632,15 +632,13 @@ def data(self, new_data): # ----------- # ### Compute new index for each remaining trace ### - new_inds = [] - for uid in uids_post_removal: - new_inds.append(new_uids.index(uid)) + new_inds = [new_uids.index(uid) for uid in uids_post_removal] # ### Compute current index for each remaining trace ### current_inds = list(range(len(traces_props_post_removal))) # ### Check whether a move is needed ### - if not all([i1 == i2 for i1, i2 in zip(new_inds, current_inds)]): + if not all(i1 == i2 for i1, i2 in zip(new_inds, current_inds)): # #### Save off index lists for moveTraces message #### msg_current_inds = current_inds @@ -2367,15 +2365,13 @@ def _build_update_params_from_batch(self): # Handle Style / Trace Indexes # ---------------------------- batch_style_commands = self._batch_trace_edits - trace_indexes = sorted(set([trace_ind for trace_ind in batch_style_commands])) + trace_indexes = sorted(set(trace_ind for trace_ind in batch_style_commands)) all_props = sorted( - set( - [ - prop - for trace_style in self._batch_trace_edits.values() - for prop in trace_style - ] + set( + prop + for trace_style in self._batch_trace_edits.values() + for prop in trace_style ) ) @@ -3999,7 +3995,7 @@ def on_change(self, callback, *args, **kwargs): # Normalize args to path tuples # ----------------------------- - arg_tuples = tuple([BaseFigure._str_to_dict_path(a) for a in args]) + arg_tuples = tuple(BaseFigure._str_to_dict_path(a) for a in args) # Initialize callbacks list # ------------------------- diff --git a/packages/python/plotly/plotly/figure_factory/_annotated_heatmap.py b/packages/python/plotly/plotly/figure_factory/_annotated_heatmap.py index ec61aac8af..59fabb10da 100644 --- a/packages/python/plotly/plotly/figure_factory/_annotated_heatmap.py +++ b/packages/python/plotly/plotly/figure_factory/_annotated_heatmap.py @@ -276,8 +276,8 @@ def get_z_mid(self): z_min = np.amin(self.z) z_max = np.amax(self.z) else: - z_min = min([v for row in self.z for v in row]) - z_max = max([v for row in self.z for v in row]) + z_min = min(v for row in self.z for v in row) + z_max = max(v for row in self.z for v in row) z_mid = (z_max + z_min) / 2 return z_mid diff --git a/packages/python/plotly/plotly/figure_factory/_county_choropleth.py b/packages/python/plotly/plotly/figure_factory/_county_choropleth.py index 93a840ad78..01445d7e2b 100644 --- a/packages/python/plotly/plotly/figure_factory/_county_choropleth.py +++ b/packages/python/plotly/plotly/figure_factory/_county_choropleth.py @@ -138,9 +138,7 @@ def _create_us_counties_df(st_to_state_name_dict, state_to_st_dict): gdf_reduced = gdf[["FIPS", "STATEFP", "COUNTY_NAME", "geometry"]] gdf_statefp = gdf_reduced.merge(df_state[["STATEFP", "STATE_NAME"]], on="STATEFP") - ST = [] - for n in gdf_statefp["STATE_NAME"]: - ST.append(state_to_st_dict[n]) + ST = [state_to_st_dict[n] for n in gdf_statefp["STATE_NAME"]] gdf_statefp["ST"] = ST return gdf_statefp, df_state diff --git a/packages/python/plotly/plotly/figure_factory/_gantt.py b/packages/python/plotly/plotly/figure_factory/_gantt.py index 8af7a43538..a9f9dd98e8 100644 --- a/packages/python/plotly/plotly/figure_factory/_gantt.py +++ b/packages/python/plotly/plotly/figure_factory/_gantt.py @@ -42,14 +42,7 @@ def validate_gantt(df): ) num_of_rows = len(df.index) - chart = [] - for index in range(num_of_rows): - task_dict = {} - for key in df: - task_dict[key] = df.ix[index][key] - chart.append(task_dict) - - return chart + return [{key: df.ix[index][key] for key in df} for index in range(num_of_rows)] # validate if df is a list if not isinstance(df, list): @@ -323,11 +316,7 @@ def gantt_colorscale( "legendgroup": "", } - index_vals = [] - for row in range(len(tasks)): - if chart[row][index_col] not in index_vals: - index_vals.append(chart[row][index_col]) - + index_vals = list({chart[row][index_col] for row in range(len(tasks))}) index_vals.sort() # compute the color for task based on indexing column @@ -437,10 +426,7 @@ def gantt_colorscale( ) if isinstance(chart[0][index_col], str): - index_vals = [] - for row in range(len(tasks)): - if chart[row][index_col] not in index_vals: - index_vals.append(chart[row][index_col]) + index_vals = list({chart[row][index_col] for row in range(len(tasks))}) index_vals.sort() @@ -664,10 +650,7 @@ def gantt_dict( "showlegend": False, } - index_vals = [] - for row in range(len(tasks)): - if chart[row][index_col] not in index_vals: - index_vals.append(chart[row][index_col]) + index_vals = list({chart[row][index_col] for row in range(len(tasks))}) index_vals.sort() @@ -971,9 +954,7 @@ def create_gantt( ) # validate gantt index column - index_list = [] - for dictionary in chart: - index_list.append(dictionary[index_col]) + index_list = [dictionary[index_col] for dictionary in chart] utils.validate_index(index_list) # Validate colors diff --git a/packages/python/plotly/plotly/figure_factory/_ohlc.py b/packages/python/plotly/plotly/figure_factory/_ohlc.py index 131d3df2d8..625c7e6373 100644 --- a/packages/python/plotly/plotly/figure_factory/_ohlc.py +++ b/packages/python/plotly/plotly/figure_factory/_ohlc.py @@ -326,9 +326,7 @@ def get_all_xy(self): ) ) if self.dates is not None: - date_dif = [] - for i in range(len(self.dates) - 1): - date_dif.append(self.dates[i + 1] - self.dates[i]) + date_dif = [self.dates[i + 1] - self.dates[i] for i in range(len(self.dates) - 1)] date_dif_min = (min(date_dif)) / 5 self.all_x = [ [x - date_dif_min, x, x, x, x, x + date_dif_min, None] diff --git a/packages/python/plotly/plotly/figure_factory/_scatterplot.py b/packages/python/plotly/plotly/figure_factory/_scatterplot.py index f7975d77db..ac28ee78fa 100644 --- a/packages/python/plotly/plotly/figure_factory/_scatterplot.py +++ b/packages/python/plotly/plotly/figure_factory/_scatterplot.py @@ -54,9 +54,8 @@ def endpts_to_intervals(endpts): "numbers." ) else: - intervals = [] # add -inf to intervals - intervals.append([float("-inf"), endpts[0]]) + intervals = [[float("-inf"), endpts[0]]] for k in range(length - 1): interval = [] interval.append(endpts[k]) @@ -382,10 +381,7 @@ def scatterplot_theme( # Check if index is made of string values if isinstance(index_vals[0], str): - unique_index_vals = [] - for name in index_vals: - if name not in unique_index_vals: - unique_index_vals.append(name) + unique_index_vals = [name for name in index_vals if name not in unique_index_vals] n_colors_len = len(unique_index_vals) # Convert colormap to list of n RGB tuples @@ -708,9 +704,7 @@ def scatterplot_theme( if len(theme) <= 1: theme.append(theme[0]) - color = [] - for incr in range(len(theme)): - color.append([1.0 / (len(theme) - 1) * incr, theme[incr]]) + color = [[1.0 / (len(theme) - 1) * incr, theme[incr]] for incr in range(len(theme))] dim = len(dataframe) fig = make_subplots(rows=dim, cols=dim, print_grid=False) diff --git a/packages/python/plotly/plotly/figure_factory/_trisurf.py b/packages/python/plotly/plotly/figure_factory/_trisurf.py index 9efc255fbb..84e3e54056 100644 --- a/packages/python/plotly/plotly/figure_factory/_trisurf.py +++ b/packages/python/plotly/plotly/figure_factory/_trisurf.py @@ -130,15 +130,9 @@ def trisurf( else: # apply user inputted function to calculate # custom coloring for triangle vertices - mean_dists = [] - for triangle in tri_vertices: - dists = [] - for vertex in triangle: - dist = color_func(vertex[0], vertex[1], vertex[2]) - dists.append(dist) - mean_dists.append(np.mean(dists)) - mean_dists = np.asarray(mean_dists) - + mean_dists = np.asarray( + [np.mean([color_func(vertex[0], vertex[1], vertex[2])for vertex in triangle]) for triangle in tri_vertices] + ) # Check if facecolors are already strings and can be skipped if isinstance(mean_dists[0], str): facecolor = mean_dists diff --git a/packages/python/plotly/plotly/figure_factory/_violin.py b/packages/python/plotly/plotly/figure_factory/_violin.py index 520a8fa551..9d880e8055 100644 --- a/packages/python/plotly/plotly/figure_factory/_violin.py +++ b/packages/python/plotly/plotly/figure_factory/_violin.py @@ -216,10 +216,7 @@ def violin_no_colorscale( """ # collect all group names - group_name = [] - for name in data[group_header]: - if name not in group_name: - group_name.append(name) + group_name = list({name for name in data[group_header]}) if sort: group_name.sort() @@ -283,10 +280,7 @@ def violin_colorscale( """ # collect all group names - group_name = [] - for name in data[group_header]: - if name not in group_name: - group_name.append(name) + group_name = list({name for name in data[group_header]}) if sort: group_name.sort() @@ -311,9 +305,7 @@ def violin_colorscale( highcolor = clrs.color_parser(colors[1], clrs.unlabel_rgb) # find min and max values in group_stats - group_stats_values = [] - for key in group_stats: - group_stats_values.append(group_stats[key]) + group_stats_values = [group_stats[key] for key in group_stats] max_value = max(group_stats_values) min_value = min(group_stats_values) @@ -386,10 +378,7 @@ def violin_dict( """ # collect all group names - group_name = [] - for name in data[group_header]: - if name not in group_name: - group_name.append(name) + group_name = list({name for name in data[group_header]}) if sort: group_name.sort() diff --git a/packages/python/plotly/plotly/figure_factory/utils.py b/packages/python/plotly/plotly/figure_factory/utils.py index cdd5657cdd..2888f1b4ab 100644 --- a/packages/python/plotly/plotly/figure_factory/utils.py +++ b/packages/python/plotly/plotly/figure_factory/utils.py @@ -172,14 +172,10 @@ def endpts_to_intervals(endpts): "numbers." ) else: - intervals = [] # add -inf to intervals - intervals.append([float("-inf"), endpts[0]]) + intervals = [[float("-inf"), endpts[0]]] for k in range(length - 1): - interval = [] - interval.append(endpts[k]) - interval.append(endpts[k + 1]) - intervals.append(interval) + intervals.append([endpts[k],endpts[k + 1]]) # add +inf to intervals intervals.append([endpts[length - 1], float("inf")]) return intervals diff --git a/packages/python/plotly/plotly/io/_orca.py b/packages/python/plotly/plotly/io/_orca.py index 2f3608bfb3..8149e542e3 100644 --- a/packages/python/plotly/plotly/io/_orca.py +++ b/packages/python/plotly/plotly/io/_orca.py @@ -1577,11 +1577,9 @@ def to_image(fig, format=None, height="None," scale=None, validate=Tru Try setting the `validate` argument to True to check for errors in the figure specification""" elif response.status_code == 525: - any_mapbox = any( - [ - trace.get("type", None) == "scattermapbox" - for trace in fig_dict.get("data", []) - ] + any_mapbox = any( + trace.get("type", None) == "scattermapbox" + for trace in fig_dict.get("data", []) ) if any_mapbox and config.mapbox_access_token is None: err_message += """ diff --git a/packages/python/plotly/plotly/matplotlylib/mpltools.py b/packages/python/plotly/plotly/matplotlylib/mpltools.py index af2e7d3861..4aed03c81e 100644 --- a/packages/python/plotly/plotly/matplotlylib/mpltools.py +++ b/packages/python/plotly/plotly/matplotlylib/mpltools.py @@ -70,7 +70,7 @@ def convert_dash(mpl_dash): # If we can't find the dash pattern in the map, convert it # into custom values in px, e.g. '7,5' -> '7px,5px' - dashpx = ",".join([x + "px" for x in dash_array]) + dashpx = ",".join(x + "px" for x in dash_array) # TODO: rewrite the convert_dash code # only strings 'solid', 'dashed', etc allowed @@ -283,7 +283,7 @@ def get_bar_gap(bar_starts, bar_ends, tol=1e-10): sides2 = bar_ends[:-1] gaps = [s2 - s1 for s2, s1 in zip(sides1, sides2)] gap0 = gaps[0] - uniform = all([abs(gap0 - gap) < tol for gap in gaps]) + uniform = all(abs(gap0 - gap) < tol for gap in gaps) if uniform: return gap0 @@ -444,7 +444,7 @@ def prep_ticks(ax, index, ax_type, props): round(tickvalues[i] - tickvalues[i - 1], 12) for i in range(1, len(tickvalues) - 1) ] - if all([dticks[i] == dticks[i - 1] for i in range(1, len(dticks) - 1)]): + if all(dticks[i] == dticks[i - 1] for i in range(1, len(dticks) - 1)): dtick = tickvalues[1] - tickvalues[0] else: warnings.warn( diff --git a/packages/python/plotly/plotly/matplotlylib/renderer.py b/packages/python/plotly/plotly/matplotlylib/renderer.py index 1a4ef28909..d84aab3492 100644 --- a/packages/python/plotly/plotly/matplotlylib/renderer.py +++ b/packages/python/plotly/plotly/matplotlylib/renderer.py @@ -203,15 +203,13 @@ def close_axes(self, ax): def draw_bars(self, bars): # sort bars according to bar containers - mpl_traces = [] - for container in self.bar_containers: - mpl_traces.append( + mpl_traces = ( [ bar_props for bar_props in self.current_bars if bar_props["mplobj"] in container - ] - ) + ] for container in self.bar_containers + ) for trace in mpl_traces: self.draw_bar(trace) diff --git a/packages/python/plotly/plotly/subplots.py b/packages/python/plotly/plotly/subplots.py index 42a37275a4..cd8319465b 100644 --- a/packages/python/plotly/plotly/subplots.py +++ b/packages/python/plotly/plotly/subplots.py @@ -534,9 +534,7 @@ def _checks(item, defaults): widths = [(max_width - horizontal_spacing * (cols - 1)) / cols] * cols elif isinstance(column_widths, (list, tuple)) and len(column_widths) == cols: cum_sum = float(sum(column_widths)) - widths = [] - for w in column_widths: - widths.append((max_width - horizontal_spacing * (cols - 1)) * (w / cum_sum)) + widths = [(max_width - horizontal_spacing * (cols - 1)) * (w / cum_sum) for w in column_widths] else: raise ValueError( """ @@ -552,9 +550,7 @@ def _checks(item, defaults): heights = [(1.0 - vertical_spacing * (rows - 1)) / rows] * rows elif isinstance(row_heights, (list, tuple)) and len(row_heights) == rows: cum_sum = float(sum(row_heights)) - heights = [] - for h in row_heights: - heights.append((1.0 - vertical_spacing * (rows - 1)) * (h / cum_sum)) + heights = [(1.0 - vertical_spacing * (rows - 1)) * (h / cum_sum) for h in row_heights] if row_dir < 0 and not use_legacy_row_heights_order: heights = list(reversed(heights)) else: diff --git a/packages/python/plotly/plotly/tests/test_core/test_update_objects/test_update_traces.py b/packages/python/plotly/plotly/tests/test_core/test_update_objects/test_update_traces.py index 3bd16adac2..adf796e230 100644 --- a/packages/python/plotly/plotly/tests/test_core/test_update_objects/test_update_traces.py +++ b/packages/python/plotly/plotly/tests/test_core/test_update_objects/test_update_traces.py @@ -238,7 +238,7 @@ def test_for_each_trace_lowercase_names(self): # Check that names were altered self.assertTrue( - all([t.name == n.lower() for t, n in zip(result_fig.data, original_names)]) + all(t.name == n.lower() for t, n in zip(result_fig.data, original_names)) ) # test update_traces diff --git a/packages/python/plotly/versioneer.py b/packages/python/plotly/versioneer.py index 2b54540510..8f51fbe55b 100644 --- a/packages/python/plotly/versioneer.py +++ b/packages/python/plotly/versioneer.py @@ -1000,11 +1000,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = set(r.strip() for r in refnames.strip("()").split(",")) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) + tags = set(r[len(TAG) :] for r in refs if r.startswith(TAG)) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -1013,7 +1013,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r"\d", r)]) + tags = set(r for r in refs if re.search(r"\d", r)) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: From 6d2435bf891a2d813fd55352bd853919a8e1632a Mon Sep 17 00:00:00 2001 From: Franz Weitkamp Date: 2019年9月27日 22:50:38 +0200 Subject: [PATCH 2/8] Even more generators and less lists --- packages/python/chart-studio/chart_studio/utils.py | 2 +- packages/python/plotly/plotly/figure_factory/_ohlc.py | 2 +- packages/python/plotly/plotly/figure_factory/_scatterplot.py | 5 +---- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/packages/python/chart-studio/chart_studio/utils.py b/packages/python/chart-studio/chart_studio/utils.py index c8da3a059d..b033d23a13 100644 --- a/packages/python/chart-studio/chart_studio/utils.py +++ b/packages/python/chart-studio/chart_studio/utils.py @@ -161,7 +161,7 @@ def validate_world_readable_and_sharing_settings(option_set): def validate_plotly_domains(option_set): - domains_not_none = [option_set[d] for d in ["plotly_domain", "plotly_api_domain"] if d in option_set and option_set[d]] + domains_not_none = (option_set[d] for d in ["plotly_domain", "plotly_api_domain"] if d in option_set and option_set[d]) if not all(d.lower().startswith("https") for d in domains_not_none): warnings.warn(http_msg, category=UserWarning) diff --git a/packages/python/plotly/plotly/figure_factory/_ohlc.py b/packages/python/plotly/plotly/figure_factory/_ohlc.py index 625c7e6373..15658a09ee 100644 --- a/packages/python/plotly/plotly/figure_factory/_ohlc.py +++ b/packages/python/plotly/plotly/figure_factory/_ohlc.py @@ -326,7 +326,7 @@ def get_all_xy(self): ) ) if self.dates is not None: - date_dif = [self.dates[i + 1] - self.dates[i] for i in range(len(self.dates) - 1)] + date_dif = (self.dates[i + 1] - self.dates[i] for i in range(len(self.dates) - 1)) date_dif_min = (min(date_dif)) / 5 self.all_x = [ [x - date_dif_min, x, x, x, x, x + date_dif_min, None] diff --git a/packages/python/plotly/plotly/figure_factory/_scatterplot.py b/packages/python/plotly/plotly/figure_factory/_scatterplot.py index ac28ee78fa..06109a76fa 100644 --- a/packages/python/plotly/plotly/figure_factory/_scatterplot.py +++ b/packages/python/plotly/plotly/figure_factory/_scatterplot.py @@ -57,10 +57,7 @@ def endpts_to_intervals(endpts): # add -inf to intervals intervals = [[float("-inf"), endpts[0]]] for k in range(length - 1): - interval = [] - interval.append(endpts[k]) - interval.append(endpts[k + 1]) - intervals.append(interval) + intervals.append([endpts[k],endpts[k + 1]]) # add +inf to intervals intervals.append([endpts[length - 1], float("inf")]) return intervals From f1208fa3d3f3aeb0ca5d2e733f97b1665aead639 Mon Sep 17 00:00:00 2001 From: Franz Weitkamp Date: 2019年9月28日 06:00:24 +0200 Subject: [PATCH 3/8] Apply black, fix unique_index_vals --- .../chart_studio/dashboard_objs/dashboard_objs.py | 2 +- .../chart_studio/grid_objs/grid_objs.py | 10 ++++++++-- .../presentation_objs/presentation_objs.py | 10 ++++++++-- packages/python/chart-studio/chart_studio/utils.py | 6 +++++- packages/python/plotly/plotly/basedatatypes.py | 4 ++-- .../python/plotly/plotly/figure_factory/_ohlc.py | 4 +++- .../plotly/plotly/figure_factory/_scatterplot.py | 14 +++++++------- .../plotly/plotly/figure_factory/_trisurf.py | 9 +++++++-- .../python/plotly/plotly/figure_factory/utils.py | 2 +- packages/python/plotly/plotly/io/_orca.py | 4 ++-- .../python/plotly/plotly/matplotlylib/renderer.py | 11 ++++++----- packages/python/plotly/plotly/subplots.py | 9 +++++++-- 12 files changed, 57 insertions(+), 28 deletions(-) diff --git a/packages/python/chart-studio/chart_studio/dashboard_objs/dashboard_objs.py b/packages/python/chart-studio/chart_studio/dashboard_objs/dashboard_objs.py index 81db46a14f..3e02310da4 100644 --- a/packages/python/chart-studio/chart_studio/dashboard_objs/dashboard_objs.py +++ b/packages/python/chart-studio/chart_studio/dashboard_objs/dashboard_objs.py @@ -296,7 +296,7 @@ def _make_all_nodes_and_paths(self): all_nodes.sort(key=lambda x: x[1]) # remove path 'second' as it's always an empty box - all_paths = [node[1] for node in all_nodes] + all_paths = [node[1] for node in all_nodes] path_second = ("second",) if path_second in all_paths: all_paths.remove(path_second) diff --git a/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py b/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py index c82897f9f3..4ca379cfef 100644 --- a/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py +++ b/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py @@ -164,7 +164,10 @@ def __init__(self, columns_or_json, fid=None): raise exceptions.InputError(err) # create columns from dataframe - all_columns = [Column(columns_or_json[name].tolist(), name) for name in columns_or_json.columns] + all_columns = [ + Column(columns_or_json[name].tolist(), name) + for name in columns_or_json.columns + ] self._columns = all_columns self.id = "" @@ -197,7 +200,10 @@ def __init__(self, columns_or_json, fid=None): ) # collect and sort all orders in case orders do not start # at zero or there are jump discontinuities between them - all_orders = [columns_or_json["cols"][column_name]["order"] for column_name in columns_or_json["cols"].keys()] + all_orders = [ + columns_or_json["cols"][column_name]["order"] + for column_name in columns_or_json["cols"].keys() + ] all_orders.sort() # put columns in order in a list diff --git a/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py b/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py index 464ce5276c..fef7918d4d 100644 --- a/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py +++ b/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py @@ -352,7 +352,11 @@ def _list_of_slides(markdown_string): text_blocks = re.split("\n-{2,}\n", markdown_string) - list_of_slides = [text for text in text_blocks if not all(char in ["\n", "-", " "] for char in text)] + list_of_slides = [ + text + for text in text_blocks + if not all(char in ["\n", "-", " "] for char in text) + ] if "\n-\n" in markdown_string: msg = ( @@ -1037,7 +1041,9 @@ def _markdown_to_presentation(self, markdown_string, style, imgStretch): slide_trans = _remove_extra_whitespace_from_line( slide_trans ) - slide_transition_list = [key for key in VALID_TRANSITIONS if key in slide_trans] + slide_transition_list = [ + key for key in VALID_TRANSITIONS if key in slide_trans + ] if slide_transition_list == []: slide_transition_list.append("slide") diff --git a/packages/python/chart-studio/chart_studio/utils.py b/packages/python/chart-studio/chart_studio/utils.py index b033d23a13..956d7fb4d3 100644 --- a/packages/python/chart-studio/chart_studio/utils.py +++ b/packages/python/chart-studio/chart_studio/utils.py @@ -161,7 +161,11 @@ def validate_world_readable_and_sharing_settings(option_set): def validate_plotly_domains(option_set): - domains_not_none = (option_set[d] for d in ["plotly_domain", "plotly_api_domain"] if d in option_set and option_set[d]) + domains_not_none = ( + option_set[d] + for d in ["plotly_domain", "plotly_api_domain"] + if d in option_set and option_set[d] + ) if not all(d.lower().startswith("https") for d in domains_not_none): warnings.warn(http_msg, category=UserWarning) diff --git a/packages/python/plotly/plotly/basedatatypes.py b/packages/python/plotly/plotly/basedatatypes.py index aa334c1a96..be31273714 100644 --- a/packages/python/plotly/plotly/basedatatypes.py +++ b/packages/python/plotly/plotly/basedatatypes.py @@ -2368,10 +2368,10 @@ def _build_update_params_from_batch(self): trace_indexes = sorted(set(trace_ind for trace_ind in batch_style_commands)) all_props = sorted( - set( + set( prop for trace_style in self._batch_trace_edits.values() - for prop in trace_style + for prop in trace_style ) ) diff --git a/packages/python/plotly/plotly/figure_factory/_ohlc.py b/packages/python/plotly/plotly/figure_factory/_ohlc.py index 15658a09ee..8d0bbe78aa 100644 --- a/packages/python/plotly/plotly/figure_factory/_ohlc.py +++ b/packages/python/plotly/plotly/figure_factory/_ohlc.py @@ -326,7 +326,9 @@ def get_all_xy(self): ) ) if self.dates is not None: - date_dif = (self.dates[i + 1] - self.dates[i] for i in range(len(self.dates) - 1)) + date_dif = ( + self.dates[i + 1] - self.dates[i] for i in range(len(self.dates) - 1) + ) date_dif_min = (min(date_dif)) / 5 self.all_x = [ [x - date_dif_min, x, x, x, x, x + date_dif_min, None] diff --git a/packages/python/plotly/plotly/figure_factory/_scatterplot.py b/packages/python/plotly/plotly/figure_factory/_scatterplot.py index 06109a76fa..9b57adf64e 100644 --- a/packages/python/plotly/plotly/figure_factory/_scatterplot.py +++ b/packages/python/plotly/plotly/figure_factory/_scatterplot.py @@ -57,7 +57,7 @@ def endpts_to_intervals(endpts): # add -inf to intervals intervals = [[float("-inf"), endpts[0]]] for k in range(length - 1): - intervals.append([endpts[k],endpts[k + 1]]) + intervals.append([endpts[k], endpts[k + 1]]) # add +inf to intervals intervals.append([endpts[length - 1], float("inf")]) return intervals @@ -234,10 +234,7 @@ def scatterplot_dict( for listy in dataframe: for listx in dataframe: # create a dictionary for index_vals - unique_index_vals = {} - for name in index_vals: - if name not in unique_index_vals: - unique_index_vals[name] = [] + unique_index_vals = {unique_index_vals[name]: [] for name in index_vals} # Fill all the rest of the names into the dictionary for name in sorted(unique_index_vals.keys()): @@ -378,7 +375,7 @@ def scatterplot_theme( # Check if index is made of string values if isinstance(index_vals[0], str): - unique_index_vals = [name for name in index_vals if name not in unique_index_vals] + unique_index_vals = list(set(name for name in index_vals)) n_colors_len = len(unique_index_vals) # Convert colormap to list of n RGB tuples @@ -701,7 +698,10 @@ def scatterplot_theme( if len(theme) <= 1: theme.append(theme[0]) - color = [[1.0 / (len(theme) - 1) * incr, theme[incr]] for incr in range(len(theme))] + color = [ + [1.0 / (len(theme) - 1) * incr, theme[incr]] + for incr in range(len(theme)) + ] dim = len(dataframe) fig = make_subplots(rows=dim, cols=dim, print_grid=False) diff --git a/packages/python/plotly/plotly/figure_factory/_trisurf.py b/packages/python/plotly/plotly/figure_factory/_trisurf.py index 84e3e54056..9425a0a449 100644 --- a/packages/python/plotly/plotly/figure_factory/_trisurf.py +++ b/packages/python/plotly/plotly/figure_factory/_trisurf.py @@ -131,8 +131,13 @@ def trisurf( # apply user inputted function to calculate # custom coloring for triangle vertices mean_dists = np.asarray( - [np.mean([color_func(vertex[0], vertex[1], vertex[2])for vertex in triangle]) for triangle in tri_vertices] - ) + [ + np.mean( + [color_func(vertex[0], vertex[1], vertex[2]) for vertex in triangle] + ) + for triangle in tri_vertices + ] + ) # Check if facecolors are already strings and can be skipped if isinstance(mean_dists[0], str): facecolor = mean_dists diff --git a/packages/python/plotly/plotly/figure_factory/utils.py b/packages/python/plotly/plotly/figure_factory/utils.py index 2888f1b4ab..c799233f13 100644 --- a/packages/python/plotly/plotly/figure_factory/utils.py +++ b/packages/python/plotly/plotly/figure_factory/utils.py @@ -175,7 +175,7 @@ def endpts_to_intervals(endpts): # add -inf to intervals intervals = [[float("-inf"), endpts[0]]] for k in range(length - 1): - intervals.append([endpts[k],endpts[k + 1]]) + intervals.append([endpts[k], endpts[k + 1]]) # add +inf to intervals intervals.append([endpts[length - 1], float("inf")]) return intervals diff --git a/packages/python/plotly/plotly/io/_orca.py b/packages/python/plotly/plotly/io/_orca.py index 8149e542e3..07a2c323fa 100644 --- a/packages/python/plotly/plotly/io/_orca.py +++ b/packages/python/plotly/plotly/io/_orca.py @@ -1577,9 +1577,9 @@ def to_image(fig, format=None, height="None," scale=None, validate=Tru Try setting the `validate` argument to True to check for errors in the figure specification""" elif response.status_code == 525: - any_mapbox = any( + any_mapbox = any( trace.get("type", None) == "scattermapbox" - for trace in fig_dict.get("data", []) + for trace in fig_dict.get("data", []) ) if any_mapbox and config.mapbox_access_token is None: err_message += """ diff --git a/packages/python/plotly/plotly/matplotlylib/renderer.py b/packages/python/plotly/plotly/matplotlylib/renderer.py index d84aab3492..45c4f015af 100644 --- a/packages/python/plotly/plotly/matplotlylib/renderer.py +++ b/packages/python/plotly/plotly/matplotlylib/renderer.py @@ -204,11 +204,12 @@ def draw_bars(self, bars): # sort bars according to bar containers mpl_traces = ( - [ - bar_props - for bar_props in self.current_bars - if bar_props["mplobj"] in container - ] for container in self.bar_containers + [ + bar_props + for bar_props in self.current_bars + if bar_props["mplobj"] in container + ] + for container in self.bar_containers ) for trace in mpl_traces: self.draw_bar(trace) diff --git a/packages/python/plotly/plotly/subplots.py b/packages/python/plotly/plotly/subplots.py index cd8319465b..691926acdb 100644 --- a/packages/python/plotly/plotly/subplots.py +++ b/packages/python/plotly/plotly/subplots.py @@ -534,7 +534,10 @@ def _checks(item, defaults): widths = [(max_width - horizontal_spacing * (cols - 1)) / cols] * cols elif isinstance(column_widths, (list, tuple)) and len(column_widths) == cols: cum_sum = float(sum(column_widths)) - widths = [(max_width - horizontal_spacing * (cols - 1)) * (w / cum_sum) for w in column_widths] + widths = [ + (max_width - horizontal_spacing * (cols - 1)) * (w / cum_sum) + for w in column_widths + ] else: raise ValueError( """ @@ -550,7 +553,9 @@ def _checks(item, defaults): heights = [(1.0 - vertical_spacing * (rows - 1)) / rows] * rows elif isinstance(row_heights, (list, tuple)) and len(row_heights) == rows: cum_sum = float(sum(row_heights)) - heights = [(1.0 - vertical_spacing * (rows - 1)) * (h / cum_sum) for h in row_heights] + heights = [ + (1.0 - vertical_spacing * (rows - 1)) * (h / cum_sum) for h in row_heights + ] if row_dir < 0 and not use_legacy_row_heights_order: heights = list(reversed(heights)) else: From 2fb6ed4da9daa890378bcca2968a728eec31477f Mon Sep 17 00:00:00 2001 From: Franz Weitkamp Date: Thu, 3 Oct 2019 12:38:40 +0200 Subject: [PATCH 4/8] Try to fix 2.7 bug --- packages/python/chart-studio/chart_studio/api/v2/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/python/chart-studio/chart_studio/api/v2/utils.py b/packages/python/chart-studio/chart_studio/api/v2/utils.py index 805b44d934..4c02295729 100644 --- a/packages/python/chart-studio/chart_studio/api/v2/utils.py +++ b/packages/python/chart-studio/chart_studio/api/v2/utils.py @@ -75,7 +75,7 @@ def validate_response(response): if isinstance(parsed_content, dict): errors = parsed_content.get("errors", []) messages = [error.get("message") for error in errors] - message = "\n".join(msg for msg in messages if msg) + message = "\n".join([msg for msg in messages if msg]) if not message: message = content if content else "No Content" From 90bb636d93aac811628d3f230bb02cff1cde1d25 Mon Sep 17 00:00:00 2001 From: Franz Weitkamp Date: Thu, 3 Oct 2019 12:55:55 +0200 Subject: [PATCH 5/8] Problem was not resolved, go back. --- packages/python/chart-studio/chart_studio/api/v2/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/python/chart-studio/chart_studio/api/v2/utils.py b/packages/python/chart-studio/chart_studio/api/v2/utils.py index 4c02295729..805b44d934 100644 --- a/packages/python/chart-studio/chart_studio/api/v2/utils.py +++ b/packages/python/chart-studio/chart_studio/api/v2/utils.py @@ -75,7 +75,7 @@ def validate_response(response): if isinstance(parsed_content, dict): errors = parsed_content.get("errors", []) messages = [error.get("message") for error in errors] - message = "\n".join([msg for msg in messages if msg]) + message = "\n".join(msg for msg in messages if msg) if not message: message = content if content else "No Content" From b6726fa794184e696c976f64943e644d67356e73 Mon Sep 17 00:00:00 2001 From: Franz Weitkamp Date: Thu, 3 Oct 2019 15:03:16 +0200 Subject: [PATCH 6/8] Even more list comprehensions. --- .../chart_studio/grid_objs/grid_objs.py | 4 +--- .../chart-studio/chart_studio/plotly/plotly.py | 9 +++------ .../presentation_objs/presentation_objs.py | 18 +++++++----------- 3 files changed, 11 insertions(+), 20 deletions(-) diff --git a/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py b/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py index 4ca379cfef..f320aa0582 100644 --- a/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py +++ b/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py @@ -292,9 +292,7 @@ def get_column_reference(self, column_name): break if column_id is None: - col_names = [] - for column in self._columns: - col_names.append(column.name) + col_names = [column.name for column in self._columns] raise _plotly_utils.exceptions.PlotlyError( "Whoops, that column name doesn't match any of the column " "names in your grid. You must pick from {cols}".format(cols=col_names) diff --git a/packages/python/chart-studio/chart_studio/plotly/plotly.py b/packages/python/chart-studio/chart_studio/plotly/plotly.py index 2258c1895f..4cf35197aa 100644 --- a/packages/python/chart-studio/chart_studio/plotly/plotly.py +++ b/packages/python/chart-studio/chart_studio/plotly/plotly.py @@ -1659,15 +1659,12 @@ def upload(cls, dashboard, filename, sharing="public", auto_open=True): @classmethod def _get_all_dashboards(cls): - dashboards = [] res = v2.dashboards.list().json() - - for dashboard in res["results"]: - if not dashboard["deleted"]: - dashboards.append(dashboard) + dashboards = [ + dashboard for dashboard in res["results"] if not dashboard["deleted"] + ] while res["next"]: res = v2.utils.request("get", res["next"]).json() - for dashboard in res["results"]: if not dashboard["deleted"]: dashboards.append(dashboard) diff --git a/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py b/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py index fef7918d4d..2131060345 100644 --- a/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py +++ b/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py @@ -974,18 +974,14 @@ def _markdown_to_presentation(self, markdown_string, style, imgStretch): raise _plotly_utils.exceptions.PlotlyError(CODE_ENV_ERROR) # find code blocks - code_indices = [] - code_blocks = [] + code_indices = [ + j for j in range(len(slide)) if slide[j : j + wdw_size] == "```" + ] + code_blocks = [ + slide[code_indices[2 * k] : code_indices[(2 * k) + 1]] + for k in range(int(len(code_indices) / 2)) + ] wdw_size = len("```") - for j in range(len(slide)): - if slide[j : j + wdw_size] == "```": - code_indices.append(j) - - for k in range(int(len(code_indices) / 2)): - code_blocks.append( - slide[code_indices[2 * k] : code_indices[(2 * k) + 1]] - ) - lang_and_code_tuples = [] for code_block in code_blocks: # validate code blocks From a64ab871c89be9615f5586fb391938567ff917e1 Mon Sep 17 00:00:00 2001 From: Franz Weitkamp Date: Fri, 4 Oct 2019 17:22:02 +0200 Subject: [PATCH 7/8] Fix UnboundLocalError of wdw_size --- .../chart_studio/presentation_objs/presentation_objs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py b/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py index 2131060345..c0e82a9737 100644 --- a/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py +++ b/packages/python/chart-studio/chart_studio/presentation_objs/presentation_objs.py @@ -973,6 +973,7 @@ def _markdown_to_presentation(self, markdown_string, style, imgStretch): if slide.count("```") % 2 != 0: raise _plotly_utils.exceptions.PlotlyError(CODE_ENV_ERROR) + wdw_size = len("```") # find code blocks code_indices = [ j for j in range(len(slide)) if slide[j : j + wdw_size] == "```" @@ -981,7 +982,6 @@ def _markdown_to_presentation(self, markdown_string, style, imgStretch): slide[code_indices[2 * k] : code_indices[(2 * k) + 1]] for k in range(int(len(code_indices) / 2)) ] - wdw_size = len("```") lang_and_code_tuples = [] for code_block in code_blocks: # validate code blocks From 45a9270130fc0fec51b6205f0223c3f8d9302cff Mon Sep 17 00:00:00 2001 From: Franz Weitkamp Date: Sat, 5 Oct 2019 08:38:09 +0200 Subject: [PATCH 8/8] Loop over values of dictionary instead of keys and then getting the values --- .../chart_studio/grid_objs/grid_objs.py | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py b/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py index f320aa0582..e8d4d7a3de 100644 --- a/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py +++ b/packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py @@ -200,22 +200,17 @@ def __init__(self, columns_or_json, fid=None): ) # collect and sort all orders in case orders do not start # at zero or there are jump discontinuities between them - all_orders = [ - columns_or_json["cols"][column_name]["order"] - for column_name in columns_or_json["cols"].keys() - ] + all_orders = [value["order"] for value in columns_or_json["cols"].values()] all_orders.sort() # put columns in order in a list ordered_columns = [] for order in all_orders: - for column_name in columns_or_json["cols"].keys(): - if columns_or_json["cols"][column_name]["order"] == order: + for value in columns_or_json["cols"].values(): + if value["order"] == order: break - ordered_columns.append( - Column(columns_or_json["cols"][column_name]["data"], column_name) - ) + ordered_columns.append(Column(value["data"], column_name)) self._columns = ordered_columns # fill in column_ids

AltStyle によって変換されたページ (->オリジナル) /