473,785 Members | 2,767 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Printing literal text of an argument

Hi all,

I've written the following simple macro called debug(aname, avalue)
that prints out the name of an expression and its value:

def debug(aname, avalue):
print aname, 'is':
pprint.pprint(a value)

An example call is:

debug('compose( f1,f2)', compose(f1,f2))

Writing the exact same thing twice (one in quotes and the other not)
sets off an alarm in my head. Is there a way to make this function take
only one argument, and use both its value and its literal form? On a
slightly different topic, is it also possible to make the macro print
the line number where the function was first called?

Thanks,

Rex

Aug 11 '05 #1
6 1397
def debug(s):
print "s"
exec(s)

The line thing i'm not so sure about. Er. Hmmm.

On Thu, 2005-08-11 at 14:04 -0700, Rex Eastbourne wrote:
Hi all,

I've written the following simple macro called debug(aname, avalue)
that prints out the name of an expression and its value:

def debug(aname, avalue):
print aname, 'is':
pprint.pprint(a value)

An example call is:

debug('compose( f1,f2)', compose(f1,f2))

Writing the exact same thing twice (one in quotes and the other not)
sets off an alarm in my head. Is there a way to make this function take
only one argument, and use both its value and its literal form? On a
slightly different topic, is it also possible to make the macro print
the line number where the function was first called?

Thanks,

Rex


Aug 11 '05 #2
[Format recovered from top posting]

Jeremy Moles <je****@emperor linux.com> writes:
On Thu, 2005-08-11 at 14:04 -0700, Rex Eastbourne wrote:
Hi all,

I've written the following simple macro called debug(aname, avalue)
that prints out the name of an expression and its value:

def debug(aname, avalue):
print aname, 'is':
pprint.pprint(a value)

An example call is:

debug('compose( f1,f2)', compose(f1,f2))

Writing the exact same thing twice (one in quotes and the other not)
sets off an alarm in my head. Is there a way to make this function take
only one argument, and use both its value and its literal form? On a
slightly different topic, is it also possible to make the macro print
the line number where the function was first called?

def debug(s):
print "s"
exec(s)


Um, no. First, I'm pretty sure you mean "print s" for the print
statement. The one you have just prints a single s. Second, exec is a
statement, not a function. The correct syntax is "exec s". The one you
used works, because an expression in parenthesies evaluates to the
value of the expression. Finally, doing an "exec s" doesn't display a
value - you need to print the results of the exec, which you can't
do. You want to use an eval here, not an exec. Eval is a function, and
returns a value. It's limited to expressions. Which will meet Rex's
stated requirements.

Of course, all this is moot because the eval (exec) happens in a
different context than the call, so the results can be radically
different than what you expect:
def debug(s): .... print s
.... print eval(s)
.... def foo(): .... x = 3
.... debug("x")
.... foo() x
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in foo
File "<stdin>", line 3, in debug
File "<string>", line 1, in ?
NameError: name 'x' is not defined
See what I mean?

You really need to pass the context to debug for it to get the right
thing:
def debug(x, glob, loc): .... print x
.... print eval(x, glob, loc)
.... def foo(): .... x = 3
.... debug("x", globals(), locals())
.... foo() x
3


You can figure out the locals via introspection (see the help for the
inspect module for more details). I'm not sure if there's a similar
way to figure out what the globals were at the point that debug is
called.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Aug 12 '05 #3
Rex Eastbourne wrote:
def debug(aname, avalue):
print aname, 'is':
pprint.pprint(a value)

use eval:

def debug(s):
print s, 'is'
pprint.pprint(e val(s))

(it does mean the arg is a string not code......)
On a
slightly different topic, is it also possible to make the macro print
the line number where the function was first called?


You can raise and catch an exception then walk up the call stack:

import sys

def debug(s):
print s, 'is'
pprint.pprint(e val(s))

try:
raise ""
except:
tb = sys.exc_info()[2]
# Find the calling frame
frame = tb.tb_frame.f_b ack
print "Called from line", frame.f_lineno

See the language reference manual sec 3.2 "Standard Type Hierarchy".
Aug 12 '05 #4
Thanks. I adapted it a bit:

def debug(foo):
print foo, 'is:'
exec('pprint.pp rint(' + foo + ')')

But I'm getting "NameError: name 'foo' is not defined," since foo is
not defined in this scope. (The function works beautifully when I'm
dealing with global variables, which is very rarely).

Any way around this?

Rex

Aug 12 '05 #5
Rex Eastbourne wrote:
Thanks. I adapted it a bit:

def debug(foo):
print foo, 'is:'
exec('pprint.pp rint(' + foo + ')')

But I'm getting "NameError: name 'foo' is not defined," since foo is
not defined in this scope. (The function works beautifully when I'm
dealing with global variables, which is very rarely).

Any way around this?


Eh, yes, but it's getting uglier...

def debug(foo):
print foo, 'is:'
frame = sys._getframe(-1)
exec 'pprint.pprint( %s)' % foo, frame.f_globals , frame.f_locals

Untested.

Reinhold
Aug 13 '05 #6
Rex -

If what you are looking for is a monitor of calls to a certain
function, check out this decorator example from the Python Wiki:

http://wiki.python.org/moin/PythonDe...fec0ff4b3653f4

This will allow you to very quickly turn on/off debugging for a given
routine, with no changes required in the calling code.

-- Paul

Aug 13 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3558
by: Steven T. Hatton | last post by:
This is from the draft of the previous version of the Standard: http://www.kuzbass.ru:8086/docs/isocpp/expr.html 2- A literal is a primary expression. Its type depends on its form (lex.literal). A string literal is an *lvalue*; all other literals are *rvalues*. -4- The operator :: followed by an identifier, a qualified-id, or an operator-function-id is a primary-expression. Its type is specified by the
16
48887
by: cyranoVR | last post by:
This is the approach I used to automate printing of Microsoft Access reports to PDF format i.e. unattended and without annoying "Save As..." dialogs, and - more importantly - without having to use a commercial program such as Adobe Acrobat and its associated API. The technique uses Ghostscript and Redirection Port Monitor - two free programs for creating PDF documents provided free by Russell Lang. The actual automation requires VBA...
7
4364
by: al | last post by:
char s = "This string literal"; or char *s= "This string literal"; Both define a string literal. Both suppose to be read-only and not to be modified according to Standard. And both have type of "const char *". Right? But why does the compiler I am using allow s to be modified, instead of generating compile error?
10
23323
by: Jeff B. | last post by:
Has anyone come across a decent algorithm for implementing word wrap features in .net printing? I have a small component that uses basic printing techniques (i.e. e.Graphics.DrawString in a PrintPage event of a PrintDocument object) to send some formatted text to the printer. However, if the lines are too long they run off the page rather than wrapping around. I'm sure I can spend the time and come up with a word wrapping algorithm but...
0
1838
by: Nigel | last post by:
I successfully create a .NET Component (Visual Basic .NET) that would print, unfortunately when used within a web browser it appears that .NET security doesn't allow you to run code that interacts with the file system (including printing) from the web browser. How do I disabled this so I can get my windows form control to work within IE? Also, do any have any printing code or know how I can implement multipage printing using the...
0
1487
by: Nigel | last post by:
The Visual Basic .NET Step by Step book has the following code and text: Imports System.Drawing.Printing Private Sub PrintText(ByVal sender As Object, ByVal ev As PrintPageEventArgs) ev.Graphics.DrawString(TextBox1.Text, New Font("Arial", 11, FontStyle.Regular), Brushes.Black, 120, 120) ev.HasMorePages = False End Sub
5
12823
by: Tom | last post by:
I am converting an old application that was printing directly to a specialized printer device (i.e. a special label printer). It was doing this by opening a file with the file path of 'LPT1:' and then using PRINT # to print directly to the printer device. Obviously, this is not going to work under VB.NET - StreamWriter won't let you open a device like LPT1: and such. I assume I am going to have to switch to the System.Drawing.Printing...
13
58752
by: stephen | last post by:
Hi all. How do I escape the "%" sign in a print statement so that it prints? Thanks. Stephen
4
8162
by: Mukesh_Singh_Nick | last post by:
I am practicing printf formatting options. I want to print out a string literal as a raw string as opposed to its special meaning. For e.g I want to print out the "%f" part in: printf("%f\n"); literally as "%f" rather than a zero value floating point/constant double (0.000000). I tried to escape the % sign but the compiler complained with a
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10329
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10152
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10092
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8974
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.