scope.cc 1.1 KB
Newer Older
Q
qiaolongfei 已提交
1 2 3 4 5
#include "paddle/framework/scope.h"

namespace paddle {
namespace framework {

6
Error Scope::CreateVariable(const std::string& name) {
Q
qiaolongfei 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
  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;
}

25
Variable* Scope::GetVariable(const std::string& name) const {
Q
qiaolongfei 已提交
26 27 28 29 30 31 32 33 34 35
  Variable* var = GetVarLocally(name);
  if (var != nullptr) {
    return var;
  } else if (parent_ != nullptr) {
    return parent_->GetVariable(name);
  } else {
    return nullptr;
  }
}

36
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
bool Scope::HaveVariable(const std::string& name) {
Q
qiaolongfei 已提交
51 52 53 54 55
  return vars_.count(name) != 0;
}

}  // namespace framework
}  // namespace paddle