Python: What does _("str") do? - python

I see this in the Django source code:
description = _("Comma-separated integers")
description = _("Date (without time)")
What does it do? I try it in Python 3.1.3 and it fails:
>>> foo = _("bar")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
foo = _("bar")
NameError: name '_' is not defined
No luck in 2.4.4 either:
>>> foo = _("bar")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in -toplevel-
foo = _("bar")
NameError: name '_' is not defined
What's going on here?

The name _ is an ordinary name like any other. The syntax _(x) is calling the function called _ with the argument x. In this case it is used as an alias for ugettext, which is defined by Django. This function is used for translation of strings. From the documentation:
Specifying translation strings: In Python code
Standard translation
Specify a translation string by using the function ugettext(). It’s convention to import this as a shorter alias, _, to save typing.
To use _ in your own code you can use an import like this:
from django.utils.translation import ugettext as _

The symbol _ is just a variable name in python, and in this case it looks like it refers to a function or other "callable" which takes a string as an argument. For example
def myfun(strng):
return "input = " + strng
_ = myfun
description = _("Comma-separated integers")

It should be noted that you cannot choose any alias to want, if you want ``makemessages```to detect the strings.

Related

Why can I not read the 'typename' after creating a namedtuple object in Python

This query is further with reference to this query
So, I am trying to execute the following code :
from collections import *
tp = namedtuple('emp', 'eid enames mob')
print(tp)
print(emp)
I can execute print(tp) and the output generated is <class '__main__.emp'>.
But when I try to execute print(emp), It generates the following exception :
Traceback (most recent call last):
File "a.py", line 5, in <module>
print(emp)
NameError: name 'emp' is not defined
What is the reason. The class emp is created. But I can not figure out how to access it directly. Or can I not ?
So basically, I can create instance of tp as tp() but not instances of emp in the same way. Why?
Option 1: Just repeat the type name when assigning to the returned type
tp = emp = namedtuple('emp', 'eid enames mob')
Option 2: Use a declarative style instead of the functional APIs
from typing import NamedTuple
class emp(NamedTuple):
eid: str
enames: str
mob: str

My question is about the functionality of the 'eval' function when this is included in a function of an imported module

I have created a simple function for reporting current values of variables in some engineering scripts, by passing the variable name in an eval() function. The argument is passed as string then the eval() reads it and reports back the value with some additional info. The function works properly in a single script. However when i am importing the same function from a module i get back an error saying that the variable has is not defined.
I have trying setting it up as a global variable but still get the same problem
def report(name,units = '-',comment ='NC'):
if type(eval(name)) == str:
print('{0:<12}= {1:^10} {2:^5} {3}'.format(name,eval(name),units,comment))
else:
print('{0:<12}= {1:8.3f} {2:^5} {3}'.format(name,eval(name),units,comment))
While trying to use the function from the imported module i get the following
>>>from reporting import*
>>> from shapes import*
>>> Iyy = rec_Iyy(40,60)
>>> report('Iyy')
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
File "C:\Users\vousvoukisi\OneDrive\11.Python\03_myScripts\design_mod\reporting.py", line 8, in report
if type(eval(name)) == str:
File "<string>", line 1, in <module>
NameError: name 'Iyy' is not defined
## while i would expect the outcome to be :
>>> %Run reporting.py
Iyy = 720000.000 - NC

How do I time how long a user takes to type input?

I'm making a game in Python and I need to find how long it takes for a user to enter their response to a prompt. I would then like to have the input stored in a variable.
I have already tried using the timeit module with no success:
import timeit
def get_input_from_user():
variable = input("Prompt: ")
time_to_respond = timeit.timeit(get_input_from_user())
This code gives the following ValueError:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\username\AppData\Local\Programs\Python\Python37-32\lib\timeit.py", line 232, in timeit
return Timer(stmt, setup, timer, globals).timeit(number)
File "C:\Users\username\AppData\Local\Programs\Python\Python37-32\lib\timeit.py", line 128, in __init__
raise ValueError("stmt is neither a string nor callable")
ValueError: stmt is neither a string nor callable
Is there another way of going about this? Thank you!
Using timeit, you can check how much time an expression takes using:
time_to_respond = timeit.timeit(get_input_from_user, number=1)
Note, no parentheses, and the argument number=1, to make sure that it only gets called once.
For example, this could return:
>>> time_to_respond
1.66159096399997
But since you want access to both the variable and the time to respond, I would suggest doing something along these lines instead, using the time module:
import time
def get_input_from_user():
s = time.time()
variable = input("Prompt: ")
e = time.time()
return e-s, variable
time_to_respond, variable = get_input_from_user()
>>> time_to_respond
2.4452149868011475
>>> variable
'hello!'

Splitting Lines in Python in a List?

I'm new-ish to Python and I'm having trouble achieving a result that I want. I'm opening a text file called urldata.txt which contains URLs that I need to break down by scheme, server, and path.
I have retrieved the data from the file:
urls = open("urldata.txt").read()
print(urls)
this returns:
http://www.google.com
https://twitter.com/search?q=%23ASUcis355
https://github.com/asu-cis-355/course-info
I want to break these URLs into 3 pieces each so that when I enter
urls.scheme()
urls.server()
urls.path()
It will return me the scheme of each URL when I enter
urls.scheme()
'http','https','https'
Then it will return the server when I enter
urls.server()
'google.com'
'twitter.com'
'github.com'
Finally, it will return the path when I enter
urls.path()
'/'
'/search?q=%23ASUcis355'
'/asu-cis-355/course-info'
I have defined a class to do this; however, I receive an error saying 'scheme() missing 1 required positional argument: 'self' Below is my class and the def parts to it that I have created.
class urls:
def __init__(self,url):
self.urls=urls
def scheme(self):
return urls.split("://")[0]
def server(self):
return urls.split("/")[2]
def path(self):
return urls.split(".com/")[1]
Any help at all is greatly appreciated!
This exists already. It's called urlparse:
from urllib.parse import urlparse
d = urlparse('https://twitter.com/search?q=%23ASUcis355')
print(d)
Output:
ParseResult(scheme='https', netloc='twitter.com', path='/search', params='', query='q=%23ASUcis355', fragment='')
If you attempt to call a class definition (what urls' is) without creating an instance of this class in Python3 then you get this error
>>> urls.scheme()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: scheme() missing 1 required positional argument: 'self'
>>>
But if you create an instance of urls and then use that instance this works as intended
>>> url_instance = urls("http://www.google.com")
>>> url_instance.scheme()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in scheme
AttributeError: type object 'urls' has no attribute 'split'
Note that this fixes your current error but your code isn't correct as is. I'll leave you to figure out what's happening with this error.
The difference between a class definition (or type) and an instance of the class has some interesting nuance but generally speaking
class Thing:
pass
is a class definition and
thing_instance = Thing()
Is an instance of the class.

NameError: name 'word' is not defined

I'm trying to make a mixWord function and I'm getting an error saying
NameError: name 'word' is not defined
What am I missing from here?
def mixWord(word):
characterList = list(word);
print characterList
import random;
random.shuffle(characterList);
print characterList;
shuffledWord = ''.join(characterList);
print shuffledWord;
Traceback (most recent call last):
File "", line 1, in
mixWord (word)
NameError: name 'word' is not defined
The problem is PEBKAC - exactly what form, is for you to find out.
That is, the code executed is not the same as the code posted; the posted code works as expected:
def mixWord(word):
characterList = list(word);
print characterList
import random;
random.shuffle(characterList);
print characterList;
shuffledWord = ''.join(characterList);
print shuffledWord;
mixWord("PEBKAC")
So, find out why:
Has the file been saved?
Has the file been saved to the correct location?
Is the file from the correct location being run?
Is the error from different code entirely?
Also try running the code directly from an IDLE buffer as that should be immune to the previous potential issue(s).
After resolving the issue, consider updating the code to not using semicolons as they are not required here and it is un-Pythonic.
I think the problem is that you are calling mixWord(word) without defining any word variable.

Categories

Resources