or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-fastscript

A fast way to turn your python function into a script

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/fastscript@0.1.x

To install, run

npx @tessl/cli install tessl/pypi-fastscript@0.1.0

0

# fastscript

1

2

A fast way to turn your python function into a script. fastscript provides a lightweight Python library that simplifies the creation of command-line interfaces from Python functions, acting as a streamlined wrapper around argparse with minimal boilerplate code.

3

4

## Package Information

5

6

- **Package Name**: fastscript

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install fastscript`

10

- **Minimum Python**: 3.6+

11

12

## Core Imports

13

14

```python

15

from fastscript import Param, call_parse, anno_parser, str2bool

16

```

17

18

Common wildcard import pattern:

19

20

```python

21

from fastscript import *

22

```

23

24

## Basic Usage

25

26

```python

27

from fastscript import *

28

29

@call_parse

30

def main(

31

msg: Param("The message", str),

32

upper: Param("Convert to uppercase?", str2bool) = False

33

):

34

"""A simple CLI script that prints a message."""

35

print(msg.upper() if upper else msg)

36

```

37

38

When you run this script:

39

40

```bash

41

$ python script.py "Hello World"

42

Hello World

43

44

$ python script.py "Hello World" --upper true

45

HELLO WORLD

46

47

$ python script.py --help

48

usage: script.py [-h] [--upper UPPER] msg

49

A simple CLI script that prints a message.

50

51

positional arguments:

52

msg The message

53

54

optional arguments:

55

-h, --help show this help message and exit

56

--upper UPPER Convert to uppercase?

57

```

58

59

## Architecture

60

61

fastscript uses function annotations and decorators to automatically generate CLI interfaces:

62

63

- **@call_parse decorator**: Transforms any function into a CLI script

64

- **Param annotations**: Define CLI argument behavior and help text

65

- **Automatic parsing**: Uses function signatures to determine positional vs optional arguments

66

- **Type conversion**: Handles automatic type conversion via Param(type=...) parameter

67

68

The library automatically determines argument types based on function defaults:

69

- Parameters with defaults become optional arguments (--flag style)

70

- Parameters without defaults become required positional arguments

71

72

## Capabilities

73

74

### CLI Decorator

75

76

Creates a command-line interface from a Python function using function annotations.

77

78

```python { .api }

79

def call_parse(func):

80

"""

81

Decorator to create a simple CLI from func using anno_parser.

82

83

Parameters:

84

- func: Function to convert to CLI script

85

86

Returns:

87

Decorated function that can be called programmatically or from CLI

88

89

Behavior:

90

- Automatically calls the function with parsed CLI arguments when script is run as __main__

91

- Function remains callable programmatically with direct arguments

92

- Uses function docstring as program description

93

- Determines argument types from Param annotations and defaults

94

"""

95

```

96

97

Usage example:

98

```python

99

@call_parse

100

def process_file(

101

filename: Param("Input file to process", str),

102

verbose: Param("Enable verbose output", str2bool) = False,

103

output: Param("Output file", str) = "result.txt"

104

):

105

"""Process a file with optional verbose output."""

106

# Function implementation

107

pass

108

```

109

110

### Parameter Annotation

111

112

Defines the behavior and help text for function parameters in CLI scripts.

113

114

```python { .api }

115

class Param:

116

"""

117

A parameter in a function used in anno_parser or call_parse.

118

119

Parameters:

120

- help: str, optional - Help text for the parameter

121

- type: type, optional - Parameter type conversion function

122

- opt: bool, optional - Whether parameter is optional (default: True)

123

- action: str, optional - argparse action type

124

- nargs: str/int, optional - Number of arguments ('*', '+', '?', or int)

125

- const: any, optional - Constant value for store_const action

126

- choices: list, optional - List of valid choices for the parameter

127

- required: bool, optional - Whether parameter is required (overrides opt)

128

129

Properties:

130

- pre: Returns '--' if optional parameter, '' if positional

131

- kwargs: Returns dict of non-None attributes excluding 'opt'

132

"""

133

```

134

135

Usage example:

136

```python

137

def process_data(

138

input_file: Param("Input data file", str),

139

format: Param("Output format", str, choices=["json", "csv", "xml"]) = "json",

140

count: Param("Number of items to process", int, nargs='?') = 10,

141

verbose: Param("Enable verbose mode", action="store_true") = False

142

):

143

pass

144

```

145

146

### Argument Parser Generator

147

148

Creates an ArgumentParser from function annotations for advanced CLI customization.

149

150

```python { .api }

151

def anno_parser(func):

152

"""

153

Look at params (annotated with Param) in func and return an ArgumentParser.

154

155

Parameters:

156

- func: Function with Param annotations to analyze

157

158

Returns:

159

argparse.ArgumentParser configured from function signature

160

161

Behavior:

162

- Examines function signature and Param annotations

163

- Creates ArgumentParser with function docstring as description

164

- Automatically determines positional vs optional arguments from defaults

165

- Configures argument types, help text, and validation from Param objects

166

"""

167

```

168

169

Usage example:

170

```python

171

def my_function(

172

name: Param("Your name", str),

173

age: Param("Your age", int) = 25

174

):

175

"""A sample function."""

176

pass

177

178

# Get the parser for manual use

179

parser = anno_parser(my_function)

180

args = parser.parse_args(['John', '--age', '30'])

181

my_function(**args.__dict__)

182

```

183

184

### String to Boolean Converter

185

186

Utility function for converting string values to boolean, commonly used with CLI arguments.

187

188

```python { .api }

189

def str2bool(v):

190

"""

191

Convert string values to boolean for CLI argument parsing.

192

193

Parameters:

194

- v: bool or str - Value to convert

195

196

Returns:

197

bool - Converted boolean value

198

199

Behavior:

200

- Returns input unchanged if already boolean

201

- Converts 'yes', 'true', 't', 'y', '1' (case-insensitive) to True

202

- Converts 'no', 'false', 'f', 'n', '0' (case-insensitive) to False

203

- Raises argparse.ArgumentTypeError for invalid string values

204

"""

205

```

206

207

Usage example:

208

```python

209

@call_parse

210

def toggle_feature(

211

enable: Param("Enable the feature", str2bool) = False

212

):

213

"""Toggle a feature on or off."""

214

if enable:

215

print("Feature enabled")

216

else:

217

print("Feature disabled")

218

219

# Command line usage:

220

# python script.py --enable yes

221

# python script.py --enable true

222

# python script.py --enable 1

223

```

224

225

## Console Scripts Integration

226

227

fastscript supports setuptools console_scripts for system-wide command installation:

228

229

### Setup Configuration

230

231

In `setup.py` or `setup.cfg`:

232

```python

233

entry_points = {

234

'console_scripts': [

235

'my-script=mypackage.module:main',

236

],

237

}

238

```

239

240

Or in `settings.ini` (fastscript style):

241

```ini

242

console_scripts = my-script=mypackage.module:main

243

```

244

245

### Script Module Pattern

246

247

```python

248

# mypackage/cli.py

249

from fastscript import *

250

251

@call_parse

252

def main(

253

input_file: Param("Input file to process", str),

254

output: Param("Output directory", str) = "./output",

255

verbose: Param("Enable verbose logging", str2bool) = False

256

):

257

"""Process input files and generate output."""

258

# Implementation

259

pass

260

261

# Entry point for console script

262

if __name__ == "__main__":

263

main()

264

```

265

266

After installation with `pip install -e .`, the script becomes available system-wide:

267

```bash

268

$ my-script input.txt --output /tmp/results --verbose true

269

```

270

271

### Built-in Console Script

272

273

fastscript includes a built-in console script for testing:

274

275

```bash

276

# Available after installing fastscript

277

$ test_fastscript "Hello World" --upper true

278

HELLO WORLD

279

```

280

281

This script is defined as `test_fastscript=fastscript.test_cli:main` and provides a working example of console script integration.

282

283

## Advanced Usage Patterns

284

285

### Complex Parameter Types

286

287

```python

288

@call_parse

289

def advanced_script(

290

files: Param("Input files", str, nargs='+'),

291

mode: Param("Processing mode", str, choices=['fast', 'thorough', 'debug']) = 'fast',

292

workers: Param("Number of worker threads", int) = 4,

293

config: Param("Configuration file", str, required=False) = None,

294

dry_run: Param("Perform dry run without changes", action='store_true') = False

295

):

296

"""Advanced script with multiple parameter types."""

297

print(f"Processing {len(files)} files in {mode} mode")

298

print(f"Using {workers} workers")

299

if config:

300

print(f"Config file: {config}")

301

if dry_run:

302

print("DRY RUN MODE - no changes will be made")

303

```

304

305

### Manual Parser Usage

306

307

```python

308

def my_function(name: Param("Name", str), count: Param("Count", int) = 1):

309

"""Example function."""

310

for i in range(count):

311

print(f"Hello, {name}!")

312

313

# Create parser manually for custom argument handling

314

parser = anno_parser(my_function)

315

parser.add_argument('--version', action='version', version='1.0.0')

316

317

# Parse arguments manually

318

args = parser.parse_args()

319

my_function(**args.__dict__)

320

```