Замена всех функций на «pass» при отправке на github

Я хотел бы создать репозиторий для проприетарного модуля python, аналогично тому, как этот пакет python mlfinlabs. Они опустошили все функции следующим образом:

          def bet_size_dynamic(current_pos, max_pos, market_price, forecast_price, cal_divergence=10, cal_bet_size=0.95,
                         func='sigmoid'):
        """
        Calculates the bet sizes, target position, and limit price as the market price and forecast price fluctuate.
        The current position, maximum position, market price, and forecast price can be passed as separate pandas.Series
        (with a common index), as individual numbers, or a combination thereof. If any one of the aforementioned arguments
        is a pandas.Series, the other arguments will be broadcast to a pandas.Series of the same length and index.
        :param current_pos: (pandas.Series, int) Current position.
        :param max_pos: (pandas.Series, int) Maximum position
        :param market_price: (pandas.Series, float) Market price.
        :param forecast_price: (pandas.Series, float) Forecast price.
        :param cal_divergence: (float) The divergence to use in calibration.
        :param cal_bet_size: (float) The bet size to use in calibration.
        :param func: (string) Function to use for dynamic calculation. Valid options are: 'sigmoid', 'power'.
        :return: (pandas.DataFrame) Bet size (bet_size), target position (t_pos), and limit price (l_p).
        """
    
        pass
    
    
    def bet_size_budget(events_t1, sides):
        """
        Calculates a bet size from the bet sides and start and end times. These sequences are used to determine the
        number of concurrent long and short bets, and the resulting strategy-independent bet sizes are the difference
        between the average long and short bets at any given time. This strategy is based on the section 10.2
        in "Advances in Financial Machine Learning". This creates a linear bet sizing scheme that is aligned to the
        expected number of concurrent bets in the dataset.
        :param events_t1: (pandas.Series) The end datetime of the position with the start datetime as the index.
        :param sides: (pandas.Series) The side of the bet with the start datetime as index. Index must match the
         'events_t1' argument exactly. Bet sides less than zero are interpretted as short, bet sides greater than zero
         are interpretted as long.
        :return: (pandas.DataFrame) The 'events_t1' and 'sides' arguments as columns, with the number of concurrent
         active long and short bets, as well as the bet size, in additional columns.
        """
    
        pass

Я нашел модуль libcst , который анализирует исходный код, и вы можете выполнять над ним операции.

Есть ли лучшая практика для этого? например: действия github? Я не могу найти другого хорошего решения.

1 ответ

  1. Действие Github для синхронизации из частного репозитория в общедоступный. Используя это действие github: https://github.com/marketplace/actions/github-repo-sync

  2. libcst(сайт проекта ) для последующего удаления функций (также в качестве шага действия github). Ниже приведен кодмод, который вы должны поставить либо

  • в папке libcst ( \Lib\site-packages\libcst\codemod\commands)
  • в вашем каталоге репо, а затем укажите его .libcst.codemod.yaml( это необходимо, если вы запускаете кодмод на действиях github):
      # String that LibCST should look for in code which indicates that the
# module is generated code.

generated_code_marker: '@generated'

# Command line and arguments for invoking a code formatter. Anything
# specified here must be capable of taking code via stdin and returning
# formatted code via stdout.

formatter: ['black', '-']

# List of regex patterns which LibCST will evaluate against filenames to
# determine if the module should be touched.

blacklist_patterns: ['.*replace_functions\.py']

# List of modules that contain codemods inside of them.

modules:

- 'libcst.codemod.commands'
- 'mycodemod' # THIS IS THE NAME OF THE FOLDER

# Absolute or relative path of the repository root, used for providing
# full-repo metadata. Relative paths should be specified with this file
# location as the base.

repo_root: '.'

поместите свой кодмод затем под:

      project_root
|--- mycodemod
         |--- __init__.py    (this is an empty file)
         |--- replace_functions.py (the codemod pasted below)

В replace_functions.pyпоместите этот фрагмент:

      from ast import Expression, literal_eval
from typing import Union

import libcst as cst
from libcst.codemod import CodemodContext, VisitorBasedCodemodCommand
from libcst.codemod.visitors import AddImportsVisitor


class ReplaceFunctionCommand(VisitorBasedCodemodCommand):
    # Add a description so that future codemodders can see what this does.
    DESCRIPTION: str = "Replaces the body of a function with pass."

    def __init__(self, context: CodemodContext) -> None:
        # Initialize the base class with context, and save our args.
        print("this happens")
        super().__init__(context)


    def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef:
        replace_function = cst.FunctionDef(
            name=updated_node.name, 
            params=cst.Parameters(), 
            body= cst.SimpleStatementSuite((cst.Pass(),)), 
            returns=None)
        
        return replace_function
Другие вопросы по тегам