MCPcopy Index your code
hub / github.com/RustPython/RustPython / calc_package

Function calc_package

crates/vm/src/import.rs:517–612  ·  view source on GitHub ↗

_calc___package__ - calculate package from globals for relative imports

(globals: Option<&PyObjectRef>, vm: &VirtualMachine)

Source from the content-addressed store, hash-verified

515
516/// _calc___package__ - calculate package from globals for relative imports
517fn calc_package(globals: Option<&PyObjectRef>, vm: &VirtualMachine) -> PyResult<String> {
518 let globals = globals.ok_or_else(|| {
519 vm.new_import_error(
520 "attempted relative import with no known parent package",
521 vm.ctx.new_utf8_str(""),
522 )
523 })?;
524
525 let package = globals.get_item("__package__", vm).ok();
526 let spec = globals.get_item("__spec__", vm).ok();
527
528 if let Some(ref pkg) = package
529 && !vm.is_none(pkg)
530 {
531 let pkg_str: PyUtf8StrRef = pkg
532 .clone()
533 .downcast()
534 .map_err(|_| vm.new_type_error("package must be a string"))?;
535 // Warn if __package__ != __spec__.parent
536 if let Some(ref spec) = spec
537 && !vm.is_none(spec)
538 && let Ok(parent) = spec.get_attr("parent", vm)
539 && !pkg_str.is(&parent)
540 && pkg_str
541 .as_object()
542 .rich_compare_bool(&parent, crate::types::PyComparisonOp::Ne, vm)
543 .unwrap_or(false)
544 {
545 let parent_repr = parent
546 .repr_utf8(vm)
547 .map(|s| s.as_str().to_owned())
548 .unwrap_or_default();
549 let msg = format!(
550 "__package__ != __spec__.parent ('{}' != {})",
551 pkg_str.as_str(),
552 parent_repr
553 );
554 let warn = vm
555 .import("_warnings", 0)
556 .and_then(|w| w.get_attr("warn", vm));
557 if let Ok(warn_fn) = warn {
558 let _ = warn_fn.call(
559 (
560 vm.ctx.new_str(msg),
561 vm.ctx.exceptions.deprecation_warning.to_owned(),
562 ),
563 vm,
564 );
565 }
566 }
567 return Ok(pkg_str.as_str().to_owned());
568 } else if let Some(ref spec) = spec
569 && !vm.is_none(spec)
570 && let Ok(parent) = spec.get_attr("parent", vm)
571 && !vm.is_none(&parent)
572 {
573 let parent_str: PyUtf8StrRef = parent
574 .downcast()

Callers 1

import_module_levelFunction · 0.85

Calls 15

newFunction · 0.85
ok_or_elseMethod · 0.80
new_import_errorMethod · 0.80
new_utf8_strMethod · 0.80
okMethod · 0.80
downcastMethod · 0.80
isMethod · 0.80
rich_compare_boolMethod · 0.80
repr_utf8Method · 0.80
is_errMethod · 0.80
get_itemMethod · 0.45
is_noneMethod · 0.45

Tested by

no test coverage detected