scope.cc 1.1 KB
Newer Older
Q
qiaolongfei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#include "paddle/framework/scope.h"

namespace paddle {
namespace framework {

Error Scope::CreateVariable(const std::string &name) {
  if (name == "") {
    return Error("Variable name should not be empty");
  }

  if (HaveVariable(name)) {
    return AlreadyCreated;
  }
  vars_[name] = std::unique_ptr<Variable>(new Variable());
  return Error();
}

Variable* Scope::GetVarLocally(const std::string& name) const {
  if (vars_.count(name)) {
    return vars_.at(name).get();
  }
  return nullptr;
}

Variable* Scope::GetVariable(const std::string &name) const {
  Variable* var = GetVarLocally(name);
  if (var != nullptr) {
    return var;
  } else if (parent_ != nullptr) {
    return parent_->GetVariable(name);
  } else {
    return nullptr;
  }
}

Variable* Scope::GetOrCreateVariable(const std::string &name) {
Q
qiaolongfei 已提交
37 38 39 40 41 42 43 44 45 46
  Variable* var = GetVariable(name);
  if (var != nullptr) {
    return var;
  }

  Error err = CreateVariable(name);
  if (!err.isOK()) {
    return nullptr;
  } else {
    return GetVariable(name);
Q
qiaolongfei 已提交
47 48 49 50 51 52 53 54 55 56
  }
}

bool Scope::HaveVariable(const std::string &name) {
  return vars_.count(name) != 0;
}

}  // namespace framework
}  // namespace paddle