Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

use generators and comprehensions instead of lists #1791

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tweakimp wants to merge 8 commits into plotly:master from tweakimp:master
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/python/chart-studio/chart_studio/api/v2/utils.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""

Expand Down Expand Up @@ -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()]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be simplified to:

all_orders = [D['order'] for D in columns_or_json["cols"].values()]

but, I'm not sure what columns_or_json looks like. I guess it's a dictionary.

Copy link
Author

@tweakimp tweakimp Oct 5, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right. Please dont mix single and double quotes :)

sursu reacted with thumbs up emoji
Copy link
Author

@tweakimp tweakimp Oct 5, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, I changed this there and below.

all_orders.sort()

# put columns in order in a list
Expand Down
2 changes: 1 addition & 1 deletion packages/python/chart-studio/chart_studio/plotly/plotly.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand Down Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
5 changes: 1 addition & 4 deletions packages/python/chart-studio/chart_studio/utils.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 4 additions & 4 deletions packages/python/plotly/_plotly_utils/basevalidators.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
10 changes: 2 additions & 8 deletions packages/python/plotly/_plotly_utils/colors/__init__.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion packages/python/plotly/codegen/figure.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions packages/python/plotly/plotly/_version.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
20 changes: 8 additions & 12 deletions packages/python/plotly/plotly/basedatatypes.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
)
)

Expand Down Expand Up @@ -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
# -------------------------
Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 5 additions & 24 deletions packages/python/plotly/plotly/figure_factory/_gantt.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand Down
4 changes: 1 addition & 3 deletions packages/python/plotly/plotly/figure_factory/_ohlc.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
12 changes: 3 additions & 9 deletions packages/python/plotly/plotly/figure_factory/_scatterplot.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
12 changes: 3 additions & 9 deletions packages/python/plotly/plotly/figure_factory/_trisurf.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading

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