| Conditions | 8 | 
| Total Lines | 64 | 
| Code Lines | 46 | 
| Lines | 0 | 
| Ratio | 0 % | 
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | # -*- coding: utf-8 -*- | ||
| 38 | def _acquire_lock(self) -> "LockFile": | ||
| 39 | """Acquire a lock by creating a lock file.""" | ||
| 40 | if self.has_lock(): | ||
| 41 | return self | ||
| 42 | |||
| 43 | parent_dir = self._lock_file_path.parent | ||
| 44 | |||
| 45 | try: | ||
| 46 | # create parent directories recursively | ||
| 47 | parent_dir.mkdir(parents=True, mode=0o770, exist_ok=True) | ||
| 48 | except OSError as e: | ||
| 49 | logger.error( | ||
| 50 | "Could not create parent dir %s for lock file. %s", | ||
| 51 | str(parent_dir), | ||
| 52 | e, | ||
| 53 | ) | ||
| 54 | return self | ||
| 55 | |||
| 56 | try: | ||
| 57 | # Open the fd with append flag to create the file | ||
| 58 | # if not exists and to avoid deleting the content | ||
| 59 | # something else wrote in it. | ||
| 60 |             self._fd = self._lock_file_path.open('a') | ||
| 61 | except Exception as e: # pylint: disable=broad-except | ||
| 62 | logger.error( | ||
| 63 | "Failed to open lock file %s. %s", | ||
| 64 | str(self._lock_file_path), | ||
| 65 | e, | ||
| 66 | ) | ||
| 67 | try: | ||
| 68 | self._fd.close() | ||
| 69 | self._fd = None | ||
| 70 | except Exception: # pylint: disable=broad-except | ||
| 71 | pass | ||
| 72 | return self | ||
| 73 | |||
| 74 | try: | ||
| 75 | self._lock_file_path.chmod(0o660) | ||
| 76 | except OSError as e: | ||
| 77 | # ignore error because it is very likely that the file exists, has | ||
| 78 | # the correct permissions but we are not the owner | ||
| 79 | logger.debug( | ||
| 80 | "Could not change permissions of lock file %s", | ||
| 81 | str(self._lock_file_path), | ||
| 82 | ) | ||
| 83 | |||
| 84 | # Try to acquire the lock. | ||
| 85 | try: | ||
| 86 | fcntl.flock(self._fd, fcntl.LOCK_EX | fcntl.LOCK_NB) | ||
| 87 | self._has_lock = True | ||
| 88 |             logger.debug("Created lock file %s.", str(self._lock_file_path)) | ||
| 89 | except BlockingIOError as e: | ||
| 90 | logger.debug( | ||
| 91 | "Failed to lock the file %s. %s", | ||
| 92 | str(self._lock_file_path), | ||
| 93 | e, | ||
| 94 | ) | ||
| 95 | try: | ||
| 96 | self._fd.close() | ||
| 97 | self._fd = None | ||
| 98 | except Exception: # pylint: disable=broad-except | ||
| 99 | pass | ||
| 100 | |||
| 101 | return self | ||
| 102 | |||
| 127 |