Skip to content

Commit 81f621d

Browse files
committed
[PythonKit] Added support for clearing the Library version or path
1 parent 6e2c366 commit 81f621d

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

PythonKit/PythonLibrary.swift

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -223,32 +223,43 @@ extension PythonLibrary {
223223
""")
224224
}
225225

226-
public static func useVersion(_ major: Int, _ minor: Int? = nil) {
226+
/// Use the Python library with the specified version.
227+
/// - Parameters:
228+
/// - major: Major version or nil to use any Python version.
229+
/// - minor: Minor version or nil to use any minor version.
230+
public static func useVersion(_ major: Int?, _ minor: Int? = nil) {
227231
self.enforceNonLoadedPythonLibrary()
228232
let version = PythonVersion(major: major, minor: minor)
229233
PythonLibrary.Environment.version.set(version.versionString)
230234
}
231235

232-
public static func useLibrary(at path: String) {
236+
/// Use the Python library at the specified path.
237+
/// - Parameter path: Path of the Python library to load or nil to use the default search path.
238+
public static func useLibrary(at path: String?) {
233239
self.enforceNonLoadedPythonLibrary()
234-
PythonLibrary.Environment.library.set(path)
240+
PythonLibrary.Environment.library.set(path ?? "")
235241
}
236242
}
237243

238244
// `PythonVersion` struct that defines a given Python version.
239245
extension PythonLibrary {
240246
private struct PythonVersion {
241-
let major: Int
247+
let major: Int?
242248
let minor: Int?
243249

244250
static let versionSeparator: Character = "."
245251

246-
init(major: Int, minor: Int?) {
252+
init(major: Int?, minor: Int?) {
253+
precondition(!(major == nil && minor != nil), """
254+
Error: The Python library minor version cannot be specified \
255+
without the major version.
256+
""")
247257
self.major = major
248258
self.minor = minor
249259
}
250260

251261
var versionString: String {
262+
guard let major = major else { return "" }
252263
var versionString = String(major)
253264
if let minor = minor {
254265
versionString += "\(PythonVersion.versionSeparator)\(minor)"
@@ -273,8 +284,10 @@ extension PythonLibrary {
273284
}
274285

275286
var value: String? {
276-
guard let value = getenv(key) else { return nil }
277-
return String(cString: value)
287+
guard let cString = getenv(key) else { return nil }
288+
let value = String(cString: cString)
289+
guard !value.isEmpty else { return nil }
290+
return value
278291
}
279292

280293
func set(_ value: String) {

0 commit comments

Comments
 (0)