I'm currently loading some configuration values into my program using
(require "config.rkt")
However, this requires that config.rkt is there. I'd like to be able to put some default values into my program and have Racket override them only if there's a local config file.
In Python I'd do something like :
try :
from local_configs import MAIN_PATH, MAX_ENTRIES
except :
MAIN_PATH = "~"
MAX_ENTRIES = 20
What's the equivalent in Racket?
You can use dynamic-require
along with an exception handler (with-handlers
).
Edit: my first proposed solution (using a failure thunk for dynamic-require
) didn't handle the case where "config.rkt"
didn't exist at all. Adding exception handling solves this.
Example:
#lang racket
;; try to require the given name, returning default on failure
(define (get-config name default)
(with-handlers ([exn:fail? (λ (e) default)])
(dynamic-require "config.rkt" name)))
(define main-path (get-config 'main-path "~"))
(define max-entries (get-config 'max-entries 20))
;; just to show what the values are
(list main-path max-entries)
Here's a sample config file:
#lang racket
(provide main-path)
(define main-path "/home")
Running the first module with the sample config module produces a result like this:
'("/home" 20)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments