Skip to content

Avoid calling GetDict twice #108

@Alexey-T

Description

@Alexey-T
function TPythonEngine.Run_CommandAsObjectWithDict(const command : AnsiString; mode : Integer; locals, globals : PPyObject) : PPyObject;
var
  m : PPyObject;
  _locals, _globals : PPyObject;
begin
  CheckPython;
  Result := nil;
  Traceback.Clear;
  CheckError(False);

  m := GetMainModule;
  if m = nil then
    raise EPythonError.Create('Run_CommandAsObject: can''t create __main__');

  if Assigned(locals) then
    _locals  := locals
  else if Assigned(FLocalVars) then
    _locals  := LocalVars
  else
    _locals  := PyModule_GetDict(m);

  if Assigned(globals) then
    _globals := globals
  else if Assigned(FGlobalVars) then
    _globals := GlobalVars
  else
    _globals := PyModule_GetDict(m);

  try
    Result := PyRun_String(PAnsiChar(CleanString(command)), mode, _globals, _locals);
    if Result = nil then
      CheckError(False);
    Py_FlushLine;
  except
    Py_FlushLine;
    if PyErr_Occurred <> nil then
      CheckError(False)
    else
      raise;
  end;
end;

here we are if EvalString/ExecString called. they give locals=nil, globals=nil. usually i have LocalVars=nil GlobalVars=nil. so PyModule_GetDict(m) is called twice! bad. pls cache it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions