在Python中是否可以只声明一个变量而不分配任何值?

发布于 2024-07-16 02:07:19 字数 768 浏览 11 评论 0原文

是否可以在Python中声明一个变量,像这样?:

var

以便它初始化为None? 看起来Python允许这样做,但是一旦你访问它,它就会崩溃。 这可能吗? 如果没有,为什么?

编辑:我想对这样的情况执行此操作:

value

for index in sequence:

   if value == None and conditionMet:
       value = index
       break

相关问题

另请参阅

Is it possible to declare a variable in Python, like so?:

var

so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?

EDIT: I want to do this for cases like this:

value

for index in sequence:

   if value == None and conditionMet:
       value = index
       break

Related Questions

See Also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

看轻我的陪伴 2024-07-23 02:07:20

在 Python 3.6+ 中,您可以使用变量注释来实现此目的:

https://www. python.org/dev/peps/pep-0526/#abstract

PEP 484 引入了类型提示,又名类型注释。 虽然它的主要焦点是函数注释,但它还引入了类型注释的概念来注释变量:

# 'captain' is a string (Note: initial value is a problem)
captain = ...  # type: str

PEP 526 旨在向 Python 添加用于注释变量类型(包括类变量和实例变量)的语法,而不是通过注释来表达它们:

captain: str  # Note: no initial value!

它似乎更直接地符合你所问的问题“在Python中是否可以只声明一个变量而不分配任何值?”

注意:Python 运行时不强制执行函数和变量类型注释。 它们可以被第三方工具使用,例如类型检查器、IDE、linter 等。

In Python 3.6+ you could use Variable Annotations for this:

https://www.python.org/dev/peps/pep-0526/#abstract

PEP 484 introduced type hints, a.k.a. type annotations. While its main focus was function annotations, it also introduced the notion of type comments to annotate variables:

# 'captain' is a string (Note: initial value is a problem)
captain = ...  # type: str

PEP 526 aims at adding syntax to Python for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments:

captain: str  # Note: no initial value!

It seems to be more directly in line with what you were asking "Is it possible only to declare a variable without assigning any value in Python?"

Note: The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.

狼性发作 2024-07-23 02:07:20

我衷心建议您阅读 其他语言有“变量”(我将其添加为相关链接)——两分钟内你就会知道 Python 有“名称”,而不是“变量”。

val = None
# ...
if val is None:
   val = any_object

I'd heartily recommend that you read Other languages have "variables" (I added it as a related link) – in two minutes you'll know that Python has "names", not "variables".

val = None
# ...
if val is None:
   val = any_object
情丝乱 2024-07-23 02:07:20

我不确定你想做什么。 Python 是一种非常动态的语言; 在实际要赋值或使用变量之前,通常不需要声明变量。 我认为您想要做的就是

foo = None

将值 None 分配给变量 foo

编辑:您真正似乎想做的就是这样:

#note how I don't do *anything* with value here
#we can just start using it right inside the loop

for index in sequence:
   if conditionMet:
       value = index
       break

try:
    doSomething(value)
except NameError:
    print "Didn't find anything"

从这么短的代码示例中判断这是否真的是正确的样式有点困难,但它是 一种更“Pythonic”的工作方式。

编辑:下面是JFS的评论(在这里发布以显示代码)

与OP的问题无关,但上面的代码可以重写为:

for item in sequence:
    if some_condition(item): 
       found = True
       break
else: # no break or len(sequence) == 0
    found = False

if found:
   do_something(item)

注意:如果 some_condition() 引发异常,则 found 未绑定。
注意:如果 len(sequence) == 0 则 item 未绑定。

上面的代码是不可取的。 其目的是说明局部变量如何工作,即在这种情况下只能在运行时确定“变量”是否“定义”。
首选方式:

for item in sequence:
    if some_condition(item):
       do_something(item)
       break

或者

found = False
for item in sequence:
    if some_condition(item):
       found = True
       break

if found:
   do_something(item)

I'm not sure what you're trying to do. Python is a very dynamic language; you don't usually need to declare variables until you're actually going to assign to or use them. I think what you want to do is just

foo = None

which will assign the value None to the variable foo.

EDIT: What you really seem to want to do is just this:

#note how I don't do *anything* with value here
#we can just start using it right inside the loop

for index in sequence:
   if conditionMet:
       value = index
       break

try:
    doSomething(value)
except NameError:
    print "Didn't find anything"

It's a little difficult to tell if that's really the right style to use from such a short code example, but it is a more "Pythonic" way to work.

EDIT: below is comment by JFS (posted here to show the code)

Unrelated to the OP's question but the above code can be rewritten as:

for item in sequence:
    if some_condition(item): 
       found = True
       break
else: # no break or len(sequence) == 0
    found = False

if found:
   do_something(item)

NOTE: if some_condition() raises an exception then found is unbound.
NOTE: if len(sequence) == 0 then item is unbound.

The above code is not advisable. Its purpose is to illustrate how local variables work, namely whether "variable" is "defined" could be determined only at runtime in this case.
Preferable way:

for item in sequence:
    if some_condition(item):
       do_something(item)
       break

Or

found = False
for item in sequence:
    if some_condition(item):
       found = True
       break

if found:
   do_something(item)
绝情姑娘 2024-07-23 02:07:20

好吧,如果你想检查一个变量是否已定义,那么为什么不检查它是否在 locals() 或 globals() 数组中呢? 重写您的代码:

for index in sequence:
   if 'value' not in globals() and conditionMet:
       value = index
       break

如果您要查找的是局部变量,则将 globals() 替换为 locals()。

Well, if you want to check if a variable is defined or not then why not check if its in the locals() or globals() arrays? Your code rewritten:

for index in sequence:
   if 'value' not in globals() and conditionMet:
       value = index
       break

If it's a local variable you are looking for then replace globals() with locals().

东京女 2024-07-23 02:07:20

我知道它来晚了,但是对于 python3,你可以使用声明一个未初始化的值,

uninitialized_value:str

# some code logic

uninitialized_value = "Value"

但是要非常小心这个技巧,因为

uninitialized_value:str

# some code logic

# WILL NOT WORK
uninitialized_value += "Extra value\n"

I know it's coming late but with python3, you can declare an uninitialized value by using

uninitialized_value:str

# some code logic

uninitialized_value = "Value"

But be very careful with this trick tho, because

uninitialized_value:str

# some code logic

# WILL NOT WORK
uninitialized_value += "Extra value\n"
那一片橙海, 2024-07-23 02:07:20

我通常将变量初始化为表示类型的东西,例如

var = ""

var = 0

如果它将是一个对象,那么在实例化它之前不要初始化它:

var = Var()

I usually initialize the variable to something that denotes the type like

var = ""

or

var = 0

If it is going to be an object then don't initialize it until you instantiate it:

var = Var()
旧话新听 2024-07-23 02:07:20

首先,我对您最初提出的问题的回答

问:如何发现变量是否在代码中的某个点定义?

答:在源文件中阅读直到您看到定义该变量的行。

但更进一步,您已经给出了一个代码示例,其中有各种排列,这些排列非常Pythonic。 您正在寻找一种扫描序列以查找与条件匹配的元素的方法,因此这里有一些解决方案:

def findFirstMatch(sequence):
    for value in sequence:
        if matchCondition(value):
            return value

    raise LookupError("Could not find match in sequence")

显然,在此示例中,您可以将 raise 替换为 return None取决于您想要实现的目标。

如果您想要与条件匹配的所有内容,您可以这样做:

def findAllMatches(sequence):
    matches = []
    for value in sequence:
        if matchCondition(value):
            matches.append(value)

    return matches

还有另一种使用 yield 执行此操作的方法,我不会费心向您展示,因为它的工作方式相当复杂。

此外,还有一种单行方法可以实现这一目标:

all_matches = [value for value in sequence if matchCondition(value)]

First of all, my response to the question you've originally asked

Q: How do I discover if a variable is defined at a point in my code?

A: Read up in the source file until you see a line where that variable is defined.

But further, you've given a code example that there are various permutations of that are quite pythonic. You're after a way to scan a sequence for elements that match a condition, so here are some solutions:

def findFirstMatch(sequence):
    for value in sequence:
        if matchCondition(value):
            return value

    raise LookupError("Could not find match in sequence")

Clearly in this example you could replace the raise with a return None depending on what you wanted to achieve.

If you wanted everything that matched the condition you could do this:

def findAllMatches(sequence):
    matches = []
    for value in sequence:
        if matchCondition(value):
            matches.append(value)

    return matches

There is another way of doing this with yield that I won't bother showing you, because it's quite complicated in the way that it works.

Further, there is a one line way of achieving this:

all_matches = [value for value in sequence if matchCondition(value)]
套路撩心 2024-07-23 02:07:20

如果我正确理解您的示例,那么您无论如何都不需要在 if 语句中引用“值”。 一旦它可以设置为任何值,您就可以跳出循环。

value = None
for index in sequence:
   doSomethingHere
   if conditionMet:
       value = index
       break 

If I'm understanding your example right, you don't need to refer to 'value' in the if statement anyway. You're breaking out of the loop as soon as it could be set to anything.

value = None
for index in sequence:
   doSomethingHere
   if conditionMet:
       value = index
       break 
爱你是孤单的心事 2024-07-23 02:07:20

如果 None 是有效的数据值,那么您需要以另一种方式访问​​该变量。 您可以使用:

var = object()

此哨兵是由 Nick Coghlan 建议的。

If None is a valid data value then you need to the variable another way. You could use:

var = object()

This sentinel is suggested by Nick Coghlan.

↘人皮目录ツ 2024-07-23 02:07:20

是否可以在Python中声明一个变量(var=None):

def decl_var(var=None):
if var is None:
    var = []
var.append(1)
return var

Is it possible to declare a variable in Python (var=None):

def decl_var(var=None):
if var is None:
    var = []
var.append(1)
return var
蒲公英的约定 2024-07-23 02:07:20

你看起来像是在尝试用 Python 编写 C 语言。 如果你想在序列中查找某些内容,Python 有内置函数可以做到这一点,例如

value = sequence.index(blarg)

You look like you're trying to write C in Python. If you want to find something in a sequence, Python has builtin functions to do that, like

value = sequence.index(blarg)
咆哮 2024-07-23 02:07:20
var_str = str()
var_int = int()
var_str = str()
var_int = int()
原谅我要高飞 2024-07-23 02:07:20

你可以用这个丑陋的单行代码来欺骗解释器 if None: var = None
它除了将变量 var 添加到局部变量字典中而不是初始化它之外什么也不做。 如果您随后尝试在函数中使用此变量,解释器将抛出 UnboundLocalError 异常。 这也适用于非常古老的 python 版本。 不简单,也不美观,但不要对 python 抱有太大期望。

You can trick an interpreter with this ugly oneliner if None: var = None
It do nothing else but adding a variable var to local variable dictionary, not initializing it. Interpreter will throw the UnboundLocalError exception if you try to use this variable in a function afterwards. This would works for very ancient python versions too. Not simple, nor beautiful, but don't expect much from python.

岁月静好 2024-07-23 02:07:19

为什么不这样做呢:

var = None

Python 是动态的,所以你不需要声明东西; 它们自动存在于分配它们的第一个范围中。 因此,您所需要的只是如上所述的常规旧赋值语句。

这很好,因为您永远不会得到未初始化的变量。 但要小心——这并不意味着您不会最终得到错误初始化的变量。 如果您将某些内容初始化为None,请确保这是您真正想要的内容,并尽可能分配更有意义的内容。

Why not just do this:

var = None

Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above.

This is nice, because you'll never end up with an uninitialized variable. But be careful -- this doesn't mean that you won't end up with incorrectly initialized variables. If you init something to None, make sure that's what you really want, and assign something more meaningful if you can.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文