您如何知道变量是否已在运行时在代码中的特定位置设置?这并不总是显而易见的,因为(1)变量可以有条件地设置,(2)变量可以有条件地删除.我正在寻找像defined()
Perl isset()
,PHP或defined?
Ruby中的东西.
if condition:
a = 42
# is "a" defined here?
if other_condition:
del a
# is "a" defined here?
Run Code Online (Sandbox Code Playgroud) 在C#中有一个null-coalescing运算符(写为??
),允许在赋值期间进行简单(短)空检查:
string s = null;
var other = s ?? "some default value";
Run Code Online (Sandbox Code Playgroud)
是否有python等价物?
我知道我能做到:
s = None
other = s if s else "some default value"
Run Code Online (Sandbox Code Playgroud)
但是有更短的方式(我不需要重复s
)?
这是非常基本的,但我编码并开始想知道是否有一种pythonic方法来检查是否存在某些东西.这是我如何做到的,如果它是真的:
var = 1
if var:
print 'it exists'
Run Code Online (Sandbox Code Playgroud)
但是当我检查是否存在某些东西时,我经常这样做:
var = 2
if var:
print 'it exists'
else:
print 'nope it does not'
Run Code Online (Sandbox Code Playgroud)
如果我所关心的只是一种浪费,似乎是一种浪费,如果没有其他东西,有没有办法检查是否存在某些东西?
例如,Python中的文件是可迭代的 - 它们遍历文件中的行.我想计算行数.
一个快速的方法是这样做:
lines = len(list(open(fname)))
Run Code Online (Sandbox Code Playgroud)
但是,这会将整个文件加载到内存中(一次).这相当违背了迭代器的目的(它只需要将当前行保留在内存中).
这不起作用:
lines = len(line for line in open(fname))
Run Code Online (Sandbox Code Playgroud)
因为发电机没有长度.
有没有办法做到这一点,没有定义计数功能?
def count(i):
c = 0
for el in i: c += 1
return c
Run Code Online (Sandbox Code Playgroud)
编辑:澄清,我明白整个文件必须阅读!我只是不想在内存中一次性=).
有没有办法检查是否定义了具有指定名称的变量(类成员或独立)?例:
if "myVar" in myObject.__dict__ : # not an easy way
print myObject.myVar
else
print "not defined"
Run Code Online (Sandbox Code Playgroud) val = ""
del val
if val is None:
print("null")
Run Code Online (Sandbox Code Playgroud)
我跑了上面的代码,但得到了NameError: name 'val' is not defined
.
如何判断变量是否为null,并避免NameError?
我正在尝试使用cx_Oracle连接到Oracle实例并执行一些DDL语句:
db = None
try:
db = cx_Oracle.connect('username', 'password', 'hostname:port/SERVICENAME')
#print(db.version)
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 1017:
print('Please check your credentials.')
# sys.exit()?
else:
print('Database connection error: %s'.format(e))
cursor = db.cursor()
try:
cursor.execute(ddl_statements)
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 955:
print('Table already exists')
if error.code == 1031:
print("Insufficient privileges - are you sure you're using the owner account?")
print(error.code)
print(error.message)
print(error.context)
cursor.close()
db.commit()
db.close()
Run Code Online (Sandbox Code Playgroud)
但是,我不太确定这里的异常处理的最佳设计是什么.
首先,我db
在try块中创建对象,以捕获任何连接错误.
但是,如果它无法连接,那么db
将不再存在 …
可能重复:
Python - 检查变量是否存在
是否有一种高效,简单和pythonic的方法来检查范围中是否存在对象?
在Python中,一切都是对象(变量,函数,类,类实例等),所以我正在寻找一个对象的泛型存在测试,无论它是什么.
我一半期望有一个exists()
内置的功能,但我找不到任何适合的账单.
每次输入s
来自表单; 在list
重新初始化.如何更改代码以将每个新附加s
到列表中?
谢谢.
class Test(webapp.RequestHandler):
def get(self):
s = self.request.get('sentence')
list = []
list.append(s)
htmlcode1 = HTML.table(list)
Run Code Online (Sandbox Code Playgroud) 我想检查是否已经定义了名称“my_name”(这是我的类对象)。我怎样才能不使用 try- except 来做到这一点:
try:
if c:
print("ok")
except NameError:
print("no")
Run Code Online (Sandbox Code Playgroud)