Shortcut for method parameter
I was wondering if there was a way to do something like this in Python:
some_method(param1="param1", param2 = somevar or None)
I want to pass the param2 if somevar is set, or None if it isn't. Basically I am looking for a sho开发者_运维问答rter way of doing this:
if somevar is None:
some_method(param1="param1")
else:
some_method(param1="param1", param2=somevar)
Keyword arguments default to what you provide them in your function definition.
def some_method(param1="param1", param2=None):
# param1 is "param1" unless some other value is passed in.
# param2 is None if some value is not passed for it.
Consider:
def print_values(first_value="Hello", second_value=None):
print first_value, second_value or "World!"
print_values() #prints Hello World!
print_values(first_value="Greetings") #prints Greetings World!
print_values(second_value="You!") # prints Hello You!
print_values(first_value="Greetings", second_value="You!")
# prints Greetings You!
If you want to print the value of a local variable, you can do so by adding the expected variable name to your definition:
print first_value, special_variable_name or second_value or "World!"
Then, if you define a variable with that name:
special_variable_name = "Sean"
print_values() # prints Hello Sean
But don't do this -- it is unexpected, magic and definitely un-Pythonic -- pass the value you need in as your second parameter instead.
If you need to be able to call it with that variable without errors, then make sure to define that variable at the top of your module.
special_variable_name = None
# ... much code later ...
special_variable_name = "Sean" #This can be commented out
print_values(second_value=special_variable_name) # prints Hello Sean
Probably you need something like defined()
of php.
It is not customary in Python to check for existence of unqualified names. Having a name either defined or not and depend on it is bad practice.
Though you may access function's local variables as locals()
and global vars as globals()
; both return a dict.
So you may pass something like locals().get('somevar', None) or globals().get('somevar', None)
to try and find somevar
first in local context, then in global context. But I discourage you from doing that unless absolutely necessary.
Aren't you intentionally trying to create a paradox by wanting to refer to potentially nonexistent variables? This to me seems very bad coding practice. The way Sean showed is the way to go. In your code, you should always first declare
somevar = None
so that if you pass that variable to your method it will be None if you haven't later on changed the value. Then in the method definition check if
param2 == None
This way you will always call the method
some_method(param1 = "param1", param2 = somevar)
and get the desired result.
精彩评论