Skip to content

Pyupgrade - #4741

Merged
fjetter merged 4 commits into
dask:mainfrom
fjetter:pyupgrade
Jun 29, 2021
Merged

fjetter merged 4 commits into
dask:mainfrom
fjetter:pyupgrade

Conversation

@fjetter

@fjetter fjetter commented Apr 23, 2021

Copy link
Copy Markdown
Member

I personally love automated formatting and I discovered this gem in the pandas pre-commit hooks. While deprecations are less common in py3 (opposed to the py2->py3 migration) they do happen. Often this boils down to slightly less verbose syntax, other times exception classes or functions are renamed, etc.

Some changes are merely for style while others, e.g. around exception classes, imho clarify things better, e.g. what's the distinction between OSError, IOError, EnvironmentError, socket.error? Nothing... since py3.3

Is this kind of thing something people would feel comfortable with or is this too much?

Comment thread distributed/_version.py Outdated
Comment on lines 87 to 89
except OSError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe this could be simplified like so?

Suggested change
except OSError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
except OSError as e:
if e.errno == errno.ENOENT:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

definitely but I didn't want to actually change things in here manually. This PR is merely for the automation part

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

even better, you can catch FileNotFoundError separately

Comment thread distributed/client.py Resolved
Comment thread distributed/comm/core.py
with suppress(Exception):
await comm.close()
raise IOError(
raise OSError(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Did we intend for these exceptions to be changed?

@jakirkham

Copy link
Copy Markdown
Member

There are a few places where this tooling seems to be changing the exceptions we are raising. This seems a little unexpected and may have surprising consequences. Is there a way to disable that?

@jacobtomlinson jacobtomlinson left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks really useful.

I especially enjoyed seeing the "%s" % var and "{}".format(var) calls being upgraded to use f-strings. Although it is interesting to note that not everything is being switched to f-string. Some things with more complex expressions seem to be stopping at .format(). Perhaps we want to refactor those so that everything is f-string?

Seeing the exceptions being changed was a little surprising. But it's my understanding that these days OSError is IOError is EnvironmentError is socket.error so switching them all out to be OSError makes sense.

The only other change I really noticed was set([1, 2, 3]) being replaced with {1, 2, 3}.

My one concern about this change is adding it to the CI via the pre-comimt check. Expecting every contributor to always write 100% modern Python just adds a little more friction. We experience this today with folks not running Black. Unless everyone uses pre-commit (which is opt-in) they will have to also run pyupgrade themselves, or maintainers will need to push another commit for them. This is only a small concern, but wanted to raise it. Perhaps we should just run this periodically ourselves instead of making it a hard requirement?

@fjetter

fjetter commented Apr 28, 2021 •

Copy link
Copy Markdown
Member Author

Some things with more complex expressions seem to be stopping at .format(). Perhaps we want to refactor those so that everything is f-string?

Yes, I guess the magic is limited to some extend. Maybe this is only a bug, or the AST is, for whatever reason, too complex, idk. If it boils down to a few remaining format calls, I could live with it

There are a few places where this tooling seems to be changing the exceptions we are raising. This seems a little unexpected and may have surprising consequences. Is there a way to disable that?

@jakirkham The exceptions we are raising are indeed altered but according to the python docs these are identical to a OSError since python 3.3, see https://docs.python.org/3/library/exceptions.html#OSError

I think it is not possible to disable this https://github.com/asottile/pyupgrade#oserror-aliases

Changed in version 3.3: EnvironmentError, IOError, WindowsError, socket.error, select.error and mmap.error have been merged into OSError, and the constructor may return a subclass.

The referred subclasses are listed in https://docs.python.org/3/library/exceptions.html#os-exceptions and include things like ConnectionError, BrokenPipeError, TimeoutError and many more but the above mentioned exceptions are aliases to OSError now, e.g.

# Python 3.8.8
In [2]: OSError is IOError
Out[2]: True

In [3]: IOError is OSError
Out[3]: True

In [4]: IOError == OSError
Out[4]: True

In [5]: OSError == IOError
Out[5]: True

In [1]: ConnectionError == OSError
Out[1]: False

In [2]: ConnectionError is OSError
Out[2]: False

Unless everyone uses pre-commit (which is opt-in) they will have to also run pyupgrade themselves, or maintainers will need to push another commit for them. This is only a small concern, but wanted to raise it. Perhaps we should just run this periodically ourselves instead of making it a hard requirement?

That is a valid concern but I figured this was already the case for black. IMHO it is the same for isort and flake8. While flake8 does not auto-format things, I personally am not able to simply write flake8 compatible code, if only for too long comments, etc.
If this is of concern, we could add a script which calls the hooks. Alternatively, pre-commit run (-a) also does the trick without actually installing the commit hook, afaik. I could live with it not being added to pre-commit :)

@fjetter

fjetter commented Apr 30, 2021

Copy link
Copy Markdown
Member Author

If this is accepted, I'll recreate the last commit which applies pyupgrade. No need for merging.

@mrocklin

Copy link
Copy Markdown
Member

This seems fine to me

@jrbourbeau jrbourbeau left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Yeah, agreed that this is fine by me. At some point I'll want to update our contributing docs to say "use pre-commit for code styling" instead of recommending it as an optional nice-to-have

Comment thread distributed/client.py
raise ValueError(
"Unexpected keyword arguments: {}".format(str(sorted(kwargs)))
)
raise ValueError(f"Unexpected keyword arguments: {str(sorted(kwargs))}")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
raise ValueError(f"Unexpected keyword arguments: {str(sorted(kwargs))}")
raise ValueError(f"Unexpected keyword arguments: {sorted(kwargs)}")

Comment on lines +158 to +170
"Occupancy -- total time: {} wall time: {}".format(
format_time(total),
format_time(total / self.scheduler.total_nthreads),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
"Occupancy -- total time: {} wall time: {}".format(
format_time(total),
format_time(total / self.scheduler.total_nthreads),
f"Occupancy -- total time: {format_time(total)} "
f"wall time: {format_time(total / self.scheduler.total_nthreads)}"

" "
+ bcolors.FAIL
+ "Retrying... (attempt {n}/{total})".format(n=retries, total=3)
+ f"Retrying... (attempt {retries}/{3})"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
+ f"Retrying... (attempt {retries}/{3})"
+ f"Retrying... (attempt {retries}/3)"

"[ {label} ] : ".format(label=cmd_dict["label"])
+ bcolors.FAIL
+ "{output}".format(output=line)
+ f"{line}"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
+ f"{line}"
+ line

@fjetter

fjetter commented Jun 29, 2021

Copy link
Copy Markdown
Member Author

@crusaderky I'll update the PR but it is probably not worth it to review individual lines. This is automatically changed. I'll rebase and we can have a look

# Optionally re-direct stdout and stderr to a logfile
if logdir is not None:
cmd = "mkdir -p {logdir} && ".format(logdir=logdir) + cmd
cmd = f"mkdir -p {logdir} && " + cmd

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
cmd = f"mkdir -p {logdir} && " + cmd
cmd = f"mkdir -p {logdir} && {cmd}"

+ "scheduler {addr}:{port}".format(addr=addr, port=port)
+ bcolors.ENDC
)
label = bcolors.BOLD + f"scheduler {addr}:{port}" + bcolors.ENDC

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
label = bcolors.BOLD + f"scheduler {addr}:{port}" + bcolors.ENDC
label = f"{bcolors.BOLD}scheduler {addr}:{port}{bcolors.ENDC}"

# Optionally redirect stdout and stderr to a logfile
if logdir is not None:
cmd = "mkdir -p {logdir} && ".format(logdir=logdir) + cmd
cmd = f"mkdir -p {logdir} && " + cmd

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
cmd = f"mkdir -p {logdir} && " + cmd
cmd = f"mkdir -p {logdir} && {cmd}"


def read(self, deserializers=None):
raise EnvironmentError
raise OSError

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
raise OSError
raise OSError()


def write(self, msg, serializers=None, on_error=None):
raise EnvironmentError
raise OSError

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
raise OSError
raise OSError()

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

out of curiosity, is this a style note or is there a functional difference?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

it's only a style note. except OSError as e will set e to an instance to OSError in both cases.


def read(self, deserializers=None):
raise EnvironmentError
raise OSError

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
raise OSError
raise OSError()


def write(self, msg, serializers=None, on_error=None):
raise EnvironmentError
raise OSError

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
raise OSError
raise OSError()

if result2 == expected2:
return
raise Exception("Expected: {}; got: {}".format(str(expected2), str(result2)))
raise Exception(f"Expected: {str(expected2)}; got: {str(result2)}")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
raise Exception(f"Expected: {str(expected2)}; got: {str(result2)}")
raise Exception(f"Expected: {expected2}; got: {result2}")


def read(self, deserializers=None):
raise EnvironmentError
raise OSError

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
raise OSError
raise OSError()


def write(self, msg, serializers=None, on_error=None):
raise EnvironmentError
raise OSError

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
raise OSError
raise OSError()

@fjetter

fjetter commented Jun 29, 2021

Copy link
Copy Markdown
Member Author

I just rebased and updated. We can either

  • merge as is and update contribution guidelines (where can I find that?)
  • remove pyupgrade from pre-commit and run this occasionally but not enforce it
  • do nothing

I suggest to do further refinements in a follow up PR

@crusaderky

Copy link
Copy Markdown
Collaborator

remove pyupgrade from pre-commit and run this occasionally but not enforce it

I think pyupgrade in the pre-commit is a bit overkill

Comment thread distributed/_version.py
@@ -84,7 +84,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=
stderr=(subprocess.PIPE if hide_stderr else None),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This file is auto-generated by versioneer and IMHO should be left untouched and excluded from pyupgrade

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'll revert. FWIW we already formatted the file in a black formatting step ~2years ago

Comment thread distributed/scheduler.py Outdated
# add more workers if more than 60% of memory is used
limit = sum([ws._memory_limit for ws in parent._workers_dv.values()])
used = sum([ws._nbytes for ws in parent._workers_dv.values()])
limit = sum(ws._memory_limit for ws in parent._workers_dv.values())

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This seems to cause some problems with cythonization

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Looks like cython doesn't like the generator expressions

@fjetter

fjetter commented Jun 29, 2021

Copy link
Copy Markdown
Member Author

I reverted the used pyupgrade version to 2.13.0 since this version worked before. The reformatting of sum([expression]) to sum(<genexpression>) is not performed by this version and that seems to create issues with cythonization

I also removed it from the pre-commit config, i.e. it would not be enforced now.

@fjetter

fjetter commented Jun 29, 2021 •

Copy link
Copy Markdown
Member Author

Based off a brief discussion on our dask maint weekly, we think this will not cause major merge conflicts so I'll go ahead and merge this now.

pyupgrade will not be added to pre-commit in this PR

@fjetter
fjetter merged commit 5dc591b into dask:main Jun 29, 2021
@fjetter
fjetter deleted the pyupgrade branch June 29, 2021 15:51
@jrbourbeau

Copy link
Copy Markdown
Member

Thanks @fjetter

fjetter added a commit to fjetter/distributed that referenced this pull request Jun 29, 2021
@crusaderky crusaderky mentioned this pull request Jun 30, 2021
mrocklin pushed a commit that referenced this pull request Jun 30, 2021
Follow-up to #4741
Related to #4989
@fjetter fjetter mentioned this pull request Sep 17, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants