My understanding of the print() in both Python and Ruby (and other languages) is that it is a method on a string (or other types). Because it is so commonly used the syntax:
print "hi"
works.
So why doesn't "hi".print() in Python or "hi".print in Ruby work?
When you do something like "hi".print(), you are implying that the string object "hi" has a method print. This is not the case. Instead, print is a function that takes a string (or other types) as input.
Ruby does have a method Object#display (doc here), which sends a representation of the object to the current output stream, or one specified as an argument.
(I find that it's hard to work with in irb if I use ; at the end of a line to suppress the printing of the return value; if I do that, display's output isn't shown, even if I flush the stream.)
It's not a method on a string. Prior to Python 3, it was a statement (just like break or import), and you could use both print "hi" and print("hi"). From Python 3, it was replaced by a function, thus you can no longer use print "hi":
Print Is A Function
The print statement has been replaced with a
print() function, with keyword arguments to replace most of the
special syntax of the old print statement (PEP 3105).
Why should it work? String classes rarely have void print methods - and you would never need them, because the standard static print function can print those strings anyway. It is important to note: method(someObject) is not necessarily the same as someObject.method().
What do you propose str.print should do?
print to stdout? how about stderr? or a file? or a serial port?
Printing to stdout is really a special case but it's so ubiquitous that sometimes it can be overlooked.
Then we'd have to specify where str should print to every time we create a string?
At the very least we'd have to say
"foo".print(sys.stdout)
Hopefully that looks awful to you too. It's a confusion of responsibilities
print isn't a method on a string in Python (or in Ruby, I believe). It's a statement (in Python 3 it's a global function). Why? For one, not everything you can print is a string. How about print 2?
In case you are more happy to use a method rather than a statement in Ruby you can use the method display ("test".display) to achieve this or define a new method easily like
class String
def print
puts self
end
end
and use it like this
"test".print
Related
I want to achieve that calling foo(2*3) prints 2*3.
The reason is that I try to create a test framework for querying data files and I want to print the query statement with the assertion result.
I tried to get it work via the inspect module but I could not make it work.
In general, the answer is "no", since the value received by the function is the result of the expression 2*3, not the expression itself. However, in Python almost anything is possible if you really want it ;-)
For simple cases you could achieve this using the inspect module like this:
#!/usr/bin/env python3
import inspect
def foo(x):
context = inspect.stack()[1].code_context[0]
print(context)
def main():
foo(2 * 3)
if __name__ == '__main__':
main()
This will print:
foo(2 * 3)
It would be trivial to get the part 2 * 3 from this string using a regular expression. However, if the function call is not on a single line, or if the line contains multiple statements, this simple trick will not work properly. It might be possible with more advanced coding, but I guess your use case is to simply print the expression in a test report or something like that? If so, this solution might be just good enough.
Because the expression is evaluated before it is passed to the function, it is not possible to print out the un-evaluated expression.
However, there is a possible workaround. You can instead pass the expression as a string and evaluate it inside the function using eval(). As a simple example:
def foo(expr):
print(expr)
return(eval(expr))
Please note however that using eval is considered bad practice.
A better solution is to simply pass a string as well as the expression, such as foo(2*3, "2*3").
How can I avoid lines like:
this_long_variable_name = this_long_variable_name.replace('a', 'b')
I thought I could avoid it by making a function, repl,
def repl(myfind, myreplace, s):
s = s.replace(myfind, myreplace)
print(s) # for testing purposes
return s
but because of stuff about the local vs. global namespaces that I don't understand, I can't get the function to return a changed value for this_long_variable_name. Here's what I've tried:
this_long_variable_name = 'abbbc'
repl('b', 'x', this_long_variable_name)
print('after call to repl, this_long_variable_name =', this_long_variable_name)
The internal print statement shows the expected: axxxc
The print statement after the call to repl show the unchanged: abbbbc
Of course, it works if I give up and accept the redundant typing:
this_long_variable_name = repl('b', 'x', this_long_variable_name)
BTW, it's not just about the length of what has to be retyped, even if the variable's name were 'a,' I would not like retyping a = a.replace(...)
Since in the function s is a parameter, I can't do:
global s
I even tried:
this_long_variable_name.repl('b', 'x')
which shows you both how little I understand and how desperate I am.
The issue you're running into is that Python strings are immutable. str.replace() returns an entirely new string, so in s = s.replace(myfind, myreplace), the name s no longer refers to the original string, which is why you don't see any change on the outside of the function's namespace.
There probably isn't a great solution to your problem. I recommend using a modern IDE or Python REPL with autocompletion to alleviate it. Trying to abuse the standard way of writing things like this may feel good to you, but it will confuse anyone else looking at your code.
Harry it does not work because inside your repl function you actually have a local copy of the content of your this_long_variable_name. This is called "pass by copy" which means python hands over a copy to the function. Unfortunately this is how python does it. Check also here:
Python: How do I pass a string by reference?
Also strings are immutable in python so if you wanna change them you always create a new modified version. Check here:
Aren't Python strings immutable?
Question would be why should you need long variable names in the first place?
I'm trying to learn Python 3. This is an example I am trying to learn from. So here I define a function to read text. Open a file, read the contents, print it, then close.
So this code runs well. The thing I don't understand, however, is why we write:
print(contents_of_file), but not read(quotes). How come it's quotes.read()? As far I can understand both print() and read() are functions and I expected both to be used the same way. What am I missing here - please help?
Is there a rule when to put stuff inside brackets and when not to?
def read_text():
quotes = open("/Users/me/text.txt", encoding = "utf-8")
contents_of_file = quotes.read()
print(contents_of_file)
quotes.close()
read_text()
print() is a function. read() is a method of the object bound to quotes. As such, read must be referred to by accessing quotes. Only then can we add parens to invoke it.
You've stumbled across the often argued definitions of functions and methods.
read() is a method that belongs to quotes (which is an instance of a class, I don't actually know the name of which). Technically, Methods belong to Objects, Functions are normally defined in a style that isn't strictly Object Orientated, or in global scope (like all C functions).
It might be worth reading up on the OOP aspects of Python, this will likely help you understand it more.
quotes is a file object. I understand you don't yet know what is an object. But try printing quotes.
print type(quotes)
This object has a function read() whose purpose is to read contents from the file.
To call a function of an object, you have to write:
object.funcName()
As this is exactly what we want, we are just calling that function. So we are writing:
quotes.read()
print doesn't belongs to any of these type of objects. So, we can call it without any object reference.
This question already has answers here:
Calling a function from string inside the same module in Python?
(2 answers)
Python function pointer
(8 answers)
Closed 9 years ago.
Im writing a python script and what I would like to do is capture the input into a variable and then use that to call a function with that name. Here is an example:
def test():
print "You want to do a test!"
option = raw_input("What do you want to do? ") #User types in test
option()
Now this isnt working since python is not seeing option as a variable but rather is trying to call the function "option". What is the bast way to go about doing this?
eval() will work, but as #MattDMo said it can be dangerous.
A much safer way to do this, if your functions are module globals:
globals()[option]()
globals() is a dictionary mapping strings to the module global objects those strings are bound to. So globals()[option] looks up the string bound to option in that dict, and returns the object; e.g., globals["test"] returns the function object for test(). Then adding () at the end calls that function object. Bingo - you're done.
You want to be very careful about running arbitrary code, but if you absolutely need to, you can use the eval() function.
What might be a better way is to give your user a menu of options, then do testing on the contents of option to see which one they picked, then run that function.
You can use python eval.
From the help page, eval evaluates the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile().
For example:
def a():
print "Hello"
inp = raw_input()
eval(inp + "()")
On entering a at the stdin, the function a will be executed. Note that this could be dangerous without any safety checks.
This is, I suppose, an actual use for bare input:
option = input("What do you want to do? ") #User types in test
option()
This is semantically equivalent to eval(raw_input()). Note that in python 3, raw_input becomes input so you will explicitly have to eval it.
The usual caveats of this type of operation being incredibly unsafe apply. But I think that's obvious from your requirement of giving the user access to run arbitrary code, so...
I like using a dict in situations like this. You can even specify a default option if the user provides an answer that isn't expected.
def buy_it():
print "use it"
def break_it():
print "fix it"
def default():
print "technologic " * 4
menu = {"buy it": buy_it, "break it": break_it}
option = raw_input("What do you want to do? ")
menu.get(option, default)()
At the IDLE interpreter I do the following with dpkt:
for ts, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
Now, when I try to see the contents of 'eth' I can either print it, or just write the variable name.
When I do:
print eth
I get:
O&áÿE(r #,òÀ¨
DYP?Jò}PªpÉ
However, when I simply write:
eth
I get the more expected output of:
Ethernet(src='<removed>', dst='<removed>', data=IP(src='<removed>', off=16384, dst='<removed>', sum=11506, len=40, p=6, ttl=128, id=29344, data=TCP(seq=2527752393, ack=218580057, win=16202, sum=62077, flags=16, dport=80, sport=51626)))
So my question is, what's the fundamental difference between doing a "print (variable)" and just writing the variable name? If I do a simple assignment (ie. "x = 100") I'll get a result of "100" for both "print x" and "x"
print(variable) equals to print(str(variable))
whereas
variable equals to print(repr(variable))
My guess is that the __repr__ and __str__ method of the class dpkt.ethernet.Ethernet produce these completely different results.
Update: Having a look at the source code tells me I am right.
There are two functions for representing data as a string in python: repr() and str().
When you use a print statement, the str function is called on whatever arguments you supplied for the print statement (and a newline is appended to the end of the result). For example, x = 100; print x will call str(x). The result ("100") will have a newline appended to it, and it will be sent to stdout.
When you execute something other than a print statement, the interpreter will print whatever value the expression yields using repr, unless the value is None, in which case nothing is printed.
In most cases, there are only subtle differences between the two. Objects, however, often define their own non-identical __str__ and __repr__ methods (which define the behavior for the str and repr built-in functions for that object). In your example, the eth object's __repr__ method must be different from the __str__ method.
I would speculate that the __str__ method is returning a binary string representation of the object to send across a network, but I can't be sure.